本文主要是介绍vue+jest快速入门,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 1. 背景
- 1.1 前置资料
- 1.2 重点知识
- 2. 快速使用
- 2.1 安装依赖
- 2.2 创建`jest.config.js`
- 2.3 添加运行命令
- 2.4 在 nodejs 中使用
- 2.5.1 配置文件示例
- 2.5.2 测试示例
- 2.5 在 vuejs 中使用
- 2.5.1 安装依赖
- 2.5.2 配置文件示例
- 2.5.3 测试示例
- 2.6 测试覆盖率
- 2.6.1 Statements
- 2.6.2 Branches
- 2.6.3 Functions
- 2.6.4 Lines
- 3. 插件
- 3.1 [jest-watch-typeahead](https://github.com/jest-community/jest-watch-typeahead)
- 4. 常见问题
- 4.1 jest: regeneratorRuntime is not defined
- 4.2 [vue-test-utils]: window is undefined
- 4.3 测试 sessionStorage/localStorage
1. 背景
本文介绍笔者使用jest
时的使用笔记,引导读者如何使用jest
实现前端的单元测试,也为笔者后续使用jest
提供参考。
1.1 前置资料
- 快速上手
1.2 重点知识
- jest-expect
- jest-describe
- jest-test/it
- jest 钩子函数
- jest 钩子函数作用域
- jest-mock
- jest-snapshot
2. 快速使用
2.1 安装依赖
npm install jest -g
npm install --save-dev babel-jest @babel/core @babel/preset-env
2.2 创建jest.config.js
示例
module.exports = {verbose: true,collectCoverage: true,collectCoverageFrom: ['**/*.{js,ts}','!**/node_modules/**','!**/__mocks__/**','!**/__tests__/**','!**/build/**','!**/vendor/**','!e2e/**',],coverageDirectory: 'coverage',clearMocks: true,moduleFileExtensions: ['js', 'ts'],roots: ['<rootDir>/__tests__'],testMatch: ['**/__tests__/**/*.test.[jt]s'],testPathIgnorePatterns: ['/node_modules/'],moduleNameMapper: {'^@root/(.*)$': '<rootDir>/$1','^@src/(.*)$': '<rootDir>/src/$1','^@mocks/(.*)$': '<rootDir>/__mocks__/$1','^@electron/(.*)$': '<rootDir>/electron/$1',},watchPathIgnorePatterns: ['coverage'],watchPlugins: ['jest-watch-typeahead/filename','jest-watch-typeahead/testname',],
}
2.3 添加运行命令
在package.json
中添加运行命令:
{"scripts": {"jest": "jest --watch","jest-updateSnapshot": "jest --updateSnapshot","jest-coverage": "jest --coverage"}
}
特别注意:
如项目没有使用git/hg
,--watch
将无法使用,请使用--watchAll
代替。
2.4 在 nodejs 中使用
2.5.1 配置文件示例
// jest.config.jsmodule.exports = {verbose: true,collectCoverage: true,collectCoverageFrom: ['**/*.{js,ts}','!**/node_modules/**','!**/__mocks__/**','!**/__tests__/**','!**/build/**','!**/vendor/**','!e2e/**',],coverageDirectory: 'coverage',clearMocks: true,moduleFileExtensions: ['js', 'ts'],roots: ['<rootDir>/__tests__'],testMatch: ['**/__tests__/**/*.test.[jt]s'],testPathIgnorePatterns: ['/node_modules/'],moduleNameMapper: {'^@root/(.*)$': '<rootDir>/$1','^@src/(.*)$': '<rootDir>/src/$1','^@mocks/(.*)$': '<rootDir>/__mocks__/$1','^@electron/(.*)$': '<rootDir>/electron/$1',},watchPathIgnorePatterns: ['coverage'],watchPlugins: ['jest-watch-typeahead/filename','jest-watch-typeahead/testname',],
}
2.5.2 测试示例
示例:
// demo.js
module.exports = class Demo {static isTrue () {return true}
}// demo.test.js
const Demo = require('@src/demo')describe('Demo', () => {beforeEach(() => {})afterEach(() => {})beforeAll(() => {})afterAll(() => {})test('isTrue', async () => {expect(Demo.isTrue()).toBeTruthy()})
})
2.5 在 vuejs 中使用
2.5.1 安装依赖
npm install --save-dev @vue/test-utils vue-jest babel-jest @babel/core @babel/preset-env
2.5.2 配置文件示例
// jest.config.jsmodule.exports = {verbose: true,moduleFileExtensions: ['js', 'ts', 'vue'],collectCoverage: true,collectCoverageFrom: ['**/*.{js,ts,vue}','!**/node_modules/**','!**/__mocks__/**','!**/__tests__/**','!**/build/**','!**/vendor/**','!e2e/**',],coverageDirectory: 'coverage',collectCoverageFrom: ['**/*.{js,ts,vue}', '!**/node_modules/**'],clearMocks: true,transform: {'.*\\.(vue)$': 'vue-jest','.*\\.(js)$': 'babel-jest',},roots: ['<rootDir>/__tests__'],moduleNameMapper: {'^@/(.*)$': '<rootDir>/src/$1','^@src/(.*)$': '<rootDir>/src/$1','^@mocks/(.*)$': ['<rootDir>/__mocks__/$1'],},testEnvironment: 'jsdom',
}
2.5.3 测试示例
describe('', () => {beforeEach(() => {})afterEach(() => {})beforeAll(() => {})afterAll(() => {})test('readJSON', async () => {})
})
2.6 测试覆盖率
2.6.1 Statements
语句覆盖率(statement coverage):是不是每个语句都被执行了。
2.6.2 Branches
分支覆盖率(branch coverage):是不是每个 if 代码块都被执行了。
JavaScript 函数参数的默认值也属于 Branches,比如:
// src/get-options.jsmodule.exports = function getOptions (port = 8080) {return {port,}
}// __tests__/get-options.test.js
const getOptions = require('@src/get-options')describe('test', () => {beforeEach(() => {})afterEach(() => {})beforeAll(() => {})afterAll(() => {})test('getOptions default', async () => {const result = getOptions()expect(result).toMatchInlineSnapshot(`Object {"port": 8080,}`)})test('getOptions 8081', async () => {const result = getOptions(8081)expect(result).toMatchInlineSnapshot(`Object {"port": 8081,}`)})
})
port = 8080
就属于 Branches 的范围内。
2.6.3 Functions
函数覆盖率(function coverage):是不是每个函数都被调用了。
该指标包括各种回调函数。
// src/run-callback.jsmodule.exports = function runCallback (callback) {return new Promise((resolve, reject) => {setTimeout(() => {callback()resolve()}, 1000)})
}// __tests__/run-callback.test.js
const runCallback = require('@src/run-callback')describe('test', () => {beforeEach(() => {})afterEach(() => {})beforeAll(() => {})afterAll(() => {})test('runCallback', async () => {const callback = jest.fn()await runCallback(callback)expect(callback).toHaveBeenCalled()}, 5000)
})
2.6.4 Lines
行覆盖率(line coverage):是不是每一行都被执行了。
3. 插件
3.1 jest-watch-typeahead
按文件名或测试名称过滤单元测试,排除干扰。
// jest.config.js
{watchPathIgnorePatterns: ['coverage'],watchPlugins: ['jest-watch-typeahead/filename','jest-watch-typeahead/testname',],
}
4. 常见问题
4.1 jest: regeneratorRuntime is not defined
修改.babelrc
,示例:
{"presets": ["@babel/preset-env", "@vue/babel-preset-jsx"],"plugins": ["@babel/plugin-transform-runtime","@babel/plugin-proposal-class-properties"],"env": {"test": {"plugins": ["@babel/plugin-transform-runtime"]}}
}
4.2 [vue-test-utils]: window is undefined
请确认jest.config.js
是否有:testEnvironment: 'jsdom'
。
4.3 测试 sessionStorage/localStorage
请阅读这里。
这篇关于vue+jest快速入门的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!