单元测试 jest 从零开始搭建简易的单元测试

js、ts使用jest经相单元测试

很多教程,但是可能我这个更加通俗易懂,特写,勿喷。

安装依赖

cnpm install ts-jest jest  @types/jest --save-dev

配置

1: 修改package.jsoin,在"scipts"添加"test": "jest", 如下

"scripts": {
    "start": "webpack-dev-server",
    "build": "webpack --mode production",
    "test": "jest"
},

2: 添加一个jest.config.js文件

填入如下内容

module.exports = {
    "moduleFileExtensions": [
        "js",
        "ts",
        "tsx"
    ],
    "transform": {
        "^.+\\.tsx?$": "ts-jest",
    },
    "testMatch": [
        "<rootDir>/tests/**/*.ts?(x)"
    ]
}

通过testMatch可以看到我们是检测 工程/tests/ 文件下的内容

一般是推荐在文件下面写测试文件,但是我比较喜欢在外面写。

然后添加一个测试文件

添加测试文件

6759456-ce23515f2248e364.png

这是我的目录,可以参考

编写测试

参考下QAQ 具体看官方文档 https://jestjs.io/docs/zh-Hans/getting-started

import { getSTyleStr, id } from '../../src/utils/utils'

test('id', () => {
    expect(id(1)).toBe(1)
    expect(id(null)).toBe(null)
    expect(id(void 0)).toBe(void 0)
})
describe('css class utils getSTyleStr', () => {
    it('带大写的属性', () => {
        expect(getSTyleStr({backgroundColor: "rgba(216,52,52,1)"}))
        .toBe('background-color: rgba(216,52,52,1);')
    })
    it('单个属性', () => {
        expect(getSTyleStr({width: "30px", height: "30px"}))
        .toBe('width: 30px;height: 30px;')
    })
})

运行

npm run test
6759456-1575938ccdd170a9.png

完美通过

这是我们如果写错了,如下


6759456-b908e0ca6159ed13.png

源码查看: https://github.com/0123cf/layout-ui

相关链接:

https://jestjs.io/docs/zh-Hans/getting-started
https://github.com/0123cf/layout-ui

--END--

转载于:https://www.jianshu.com/p/a2cfb462f583

猜你喜欢

转载自blog.csdn.net/weixin_33716557/article/details/91218413
今日推荐