需要如下库支持
- jest jest 的核心
- babel-jest .js/.jsx/.tsx 文件支持需要
- @babel/core babel-jest 依赖,babel 核心
- ts-jest .ts 文件支持需要
- @types/jest TS 类型支持
- vue-jest@next .vue 文件支持需要
- @vue/test-utils@next .spec/.test 渲染 components 以及 vue 运行支持需要
- @babel/preset-env jest 不支持 ES6/ESM 模块规则,用以支持转换
- @testing-library/jest-dom 支持断言 DOM 的状态以及 class 等相关内容
npm install --save-dev @babel/core @babel/preset-env @types/jest @testing-library/jest-dom @vue/test-utils@next vue-jest@next babel-jest ts-jest jest
复制代码
注意添加 babel.config.js 文件并写入如下内容
module.exports = {
presets: ["@babel/preset-env"],
};
复制代码
Jest 初始化
jest 部分也比较简单,可以使用 npx 初始化
npx jest --init
复制代码
也可以在 package.json 的 script 里添加命令再执行 npm run jest:init
"scripts": {
"jest:init": "jest --init"
}
复制代码
还可以手动创建 jest.config.js 文件,添加如下内容
module.exports = {
coverageProvider: "v8",
//testEnvironment :"jsdom",
//或在测试文件头部
/**
* @jest-environment jsdom
*/
globals: {
"vue-jest": {
babelConfig: false,
tsConfig: {
importHelpers: true,
},
},
},
moduleFileExtensions: ["js", "json", "jsx", "ts", "tsx", "node", "vue"],
transform: {
"^.+\.vue$": "vue-jest",
"^.+\.ts$": "ts-jest",
"^.+\.js$": "babel-jest",
"^.+\.[jt]sx?$": "babel-jest"
},
};
复制代码
完成以上步骤之后就可以在 package.json 添加 jest 运行命令了
"scripts": {
"jest:unit": "jest"
}
加入puppeteer yarn add puppeteer jest-puppeteer -D jest.config.js 加入
preset: "jest-puppeteer"
新建jest-puppeteer.config.js
module.exports = {
launch: {
dumpio: true,
headless: process.env.HEADLESS !== 'false',
},
browserContext: 'default',
}
测试 demo.spec.js
const puppeteer = require('puppeteer');
test('baidu title is correct', async () => {
const browser = await puppeteer.launch({ headless: false, slowMo: 250 });
const page = await browser.newPage();
await page.goto('https://baidu.com');
await page.setViewport({
width: 1366,
height: 768 * 2
});
const title = await page.title();
page.on('console', msg => console.log('PAGE LOG:', msg.text()));
expect(title).toBe('百度一下,你就知道');
await browser.close();
});