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

发表于:2022-9-29 09:46

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:正经修行人    来源:稀土掘金

  安装依赖
  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/ 文件下的内容。一般是推荐在文件下面写测试文件,但是我比较喜欢在外面写。然后添加一个测试文件。
  添加测试文件
  这是我的目录,可以参考。
  编写测试
  参考下QAQ  具体看官方文档 jestjs.io/docs/zh-Han…
  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
  如果我们写错了,这时候:
  本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号