js-自动化测试-单元测试

901 阅读4分钟

来吧 先上图 (贫穷如我的懒癌晚期)

测试.png

测试其实大致分为两数:白盒测试、黑盒测试。

白盒测试:白盒测试又称结构测试、透明盒测试、逻辑驱动测试或基于代码的测试。白盒测试是一种测试用例设计方法,盒子指的是被测试的软件,白盒指的是盒子是可视的,即清楚盒子内部的东西以及里面是如何运作的。
黑盒测试: 黑盒测试,它是通过测试来检测每个功能是否都能正常使用。黑盒测试着眼于程序外部结构,不考虑内部逻辑结构,主要针对软件界面和软件功能进行测试。
黑盒测试一般交给测试人员,而作为开发人员的我们一般要使用白盒测试来保障代码的稳定性。
本文主要讲白盒测试,单元测试作为我们最小的测试单元,一般分为两种:方法测试、组件测试。继而往上是集成测试,单元测试测试通过后,将代码提交到代码库里面,从而进行测试,看提交代码是否影响到其它功能。再往上就是系统测试,涉及到硬件,环境等。还有就是验收测试,一般是给产品、使用者进行验收。
我们一个完善的前端工程是由各个子功能构成的,我们在多人协作开发的过程中,要保证自己所开发的功能确保没有问题,并且对其它人没有影响。
良好的开发习惯:功能开发>单元测试>确认测试通过>提测。
目前公司大多数开发习惯:测试驱动开发TDD(test-driven development)就是需求评审>技术评审>测试用例评审>开发Ing,这样做的好处是目标性强,得出的代码质量有保证。

种草个网站testingjavascript.com/

这个网站上把测试分成四类:
静态类型,拼写错误和语法错误栓测( eslint、ts)
编写关键行为和功能的有效单元测试:方法测试(jest)、组件测试(react: react testing library, vue: Mocha + Chai + Vue-Test-Utils)
集成测试,全面审核程序,确保多个单元可以协同工作
e2e 端到端测试,自动完成整套流程操作,非依赖用户行为(puppeteer)

jest

api地址:www.jestjs.cn/docs/gettin… demo: npm install --save-dev jest
单例测试

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

组测试

test('null', () => {
  const n = null;
  expect(n).toBeNull();
  expect(n).toBeDefined();
  expect(n).not.toBeUndefined();
  expect(n).not.toBeTruthy();
  expect(n).toBeFalsy();
});

单元测试要覆盖全面,考虑多种异常情况,让方法的产生结果在可控范围内。
异步处理

test('the data is peanut butter', done => {
  function callback(data) {
    try {
      expect(data).toBe('peanut butter');
      done();
    } catch (error) {
      done(error);
    }
  }

  fetchData(callback);
});

promise

test('the fetch fails with an error', () => {
  expect.assertions(1);
  return fetchData().catch(e => expect(e).toMatch('error'));
});

目前jest基本上满足了我们所有的测试场景,小伙伴们 补文档吧 vue: cn.vuejs.org/v2/cookbook… react:react.docschina.org/docs/testin… end.

补个jest的坑

我天真的装完jest他的报错是这样的 主要是“Jest encountered an unexpected token”

 Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

开发背景:ts

npm install jest typescript ts-jest @types/jest
npm install --save-dev babel-jest babel-core@^7.0.0-0 @babel/core
npm install babel-plugin-styled-components

配置package.json

 "scripts": {
    "serve": "vue-cli-service serve",
    "build": "rimraf dist && rollup -c rollup.config.js",
    "lint": "vue-cli-service lint",
    "test": "jest",
    "init": "ts-jest config:init"
  },

执行 npm run init
npm run init 之后成生jest.config.js文件
配置 jest.config.js

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  transform: {
    "^.+\\.(js|jsx)$": "babel-jest",
  },
  testRegex: '(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$',
  reporters: ["default"],
  
  collectCoverageFrom: [
    '<rootDir>/src/*.{js,jsx}'
  ],
  moduleNameMapper: {
    'assets/images/.+?\\.svg$': '<rootDir>/test/__mocks__/svgMock.js',
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga|ogg)$': '<rootDir>/test/__mocks__/fileMock.js',
    '\\.(css|less|scss)$': '<rootDir>/test/__mocks__/styleMock.js',
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  coverageReporters: ["json", "lcov", "text", "clover"],
  transformIgnorePatterns: ["<rootDir>/node_modules/(?!(lodash-es|other-es-lib))"]
};

配置babel.config.js

module.exports = {
  presets: ["@vue/cli-plugin-babel/preset"],
  plugins: [
    '@babel/plugin-proposal-class-properties',
    "babel-plugin-styled-components",
    "@babel/plugin-syntax-dynamic-import"
  ],
  env: {
    test: {
      plugins: [
        "@babel/plugin-proposal-class-properties",
        ["babel-plugin-styled-components", { "displayName": true }],
        "@babel/plugin-syntax-dynamic-import"
      ],
      presets: ["@vue/cli-plugin-babel/preset"]
    },
  }
};

然后就ok了呀

image.png