1.在本机的某个目录下,创建一个文件,命名“jesttest”
2.使用visual studio code2打开这个文件
3.在visual studio code2的terminal中执行命令npm init
haha@jesttest$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (jesttest)
version: (1.0.0)
description: test
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /Users/lihong/Documents/jesttest/package.json:
{
"name": "jesttest",
"version": "1.0.0",
"description": "test",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes) yes
输入yes后,目录中会出现package.json配置文件
4.执行命令安装相关依赖:jest、babel-jest、babel-core、babel-preset-env、regenerator-runtime、@babel/runtime、@babel/plugin-transform-runtime、@babel/preset-env
npm install -D jest babel-jest babel-core babel-preset-env regenerator-runtime
npm i --save-dev @babel/plugin-transform-runtime
npm i --save-dev @babel/preset-env
npm install @babel/runtime
5.在项目的根目录下添加.babelrc文件,并在文件复制如下内容:
{
"presets": ["@babel/preset-env"],
"plugins": [
["@babel/transform-runtime"]
]
}
6.打开package.json文件,将script下的test的值修改为jest:
"scripts": {
"test": "jest"
}
7.在根目录下添加src和test文件夹
src文件夹下新建文件unitTestSrc.js,内容为:
export default {
sum(a, b) {
return a + b;
}
}
test文件夹下新建文件unitTestSrc.test.js,内容为:
import functions from '../src/unitTestSrc';
test('sum(2 + 2) 等于 4', () => {
expect(functions.sum(2, 2)).toBe(4);
})
- 在terminal执行命令:npm run test,示例test脚本可以成功运行。
> jesttest@1.0.0 test /Users/lihong/Documents/jesttest
> jest
PASS test/unitTestSrc.test.js
✓ sum(2 + 2) 等于 4 (4ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.134s
Ran all test suites.
- 下载实际项目中需要测试的包:
npm i --save @xsl/utils --registry=https://npm.xingshulin.com/
下载编写用例需要的包:
npm install axios
npm install logger
接下来就可以编写自己的测试用用例啦,记得用例名必须以test.js结尾,不然jest框架不会运行它。
中途遇到问题:
1).未安装
npm i --save-dev @babel/plugin-transform-runtime
npm i --save-dev @babel/preset-env
及未在.babelrc将配置成
{
"presets": ["@babel/preset-env"],
"plugins": [
["@babel/transform-runtime"]
]
}
时会报错:regeneratorRuntime is not defined
2). axios请求报 ERROR: Cross origin http://localhost forbidden
这是因为axios的版本太低造成的,运行下面命令就能解决:
npm install axios
在这个问题上耗费了很多时间,一直在百度相关问题,还是没有找到答案,后来是牛人帮忙解决的,发现版本比较低,所以以后碰到类似的问题,可以往版本的方向考虑一下。
3)Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:
同样百度了很久之后,才发现时自己的vpn没有开,能连接上服务才怪呢。所以不能一头扎到问题里,只知道百度,还要多思考一下可能的原因,环境啊,之类的。
参考链接:https://www.jianshu.com/p/b169e3756f71