lsekfe 发表于 2022-9-29 14:09:59

jest 如何从0-1搭建单元测试?

安装依赖
<font size="3">cnpm install ts-jest jest@types/jest --save-dev</font>配置
  1、修改package.jsoin,在"scipts"添加"test": "jest", 如下:

<font size="3">"scripts": {

      "start": "webpack-dev-server",

      "build": "webpack --mode production",

      "test": "jest"

  }</font>2、添加一个jest.config.js文件
  填入如下内容:

<font size="3">module.exports = {

      "moduleFileExtensions": [

        "js",

        "ts",

        "tsx"

      ],

      "transform": {

        "^.+\\.tsx?[      DISCUZ_CODE_2      ]quot;: "ts-jest",

      },

      "testMatch": [

        "<rootDir>/tests/**/*.ts?(x)"

      ]

  }</font>通过testMatch可以看到我们是检测 工程/tests/ 文件下的内容。一般是推荐在文件下面写测试文件,但是我比较喜欢在外面写。然后添加一个测试文件。
  添加测试文件


这是我的目录,可以参考。
  编写测试
  参考下QAQ具体看官方文档 jestjs.io/docs/zh-Han…

<font size="3">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;')

      })

  })</font>查看效果
<font size="3">npm run test</font>
如果我们写错了,这时候:


页: [1]
查看完整版本: jest 如何从0-1搭建单元测试?