ts-jest 从陌生到相识

ts-jest 是一款众所周知的单元测试框架。

纯ts项目 集成手法

  1. 首先 往 package.json 中加入如下主料
  "scripts": {
    "test": "jest --passWithNoTests"
  },
 "devDependencies": {
    "typescript": "*",
    "ts-jest": "*"
  }
复制代码
  1. 然后 在项目根目录下 增加 jest.config.js 文件, 配方如下:
module.exports = {
  preset: "ts-jest",
  roots: [
    "<rootDir>/__tests__"
  ],
  transform: {
    "^.+\\.(t|j)sx?$": "ts-jest",
  },
  transformIgnorePatterns: [
    "node_modules"
  ]
};
复制代码
  1. 然后在项目根目录 tests 文件夹下, 补充 .test.ts 结尾的测试文件。

  2. 测试文件写完后,以 yarn test 收获 ✔️ 或者 ×。

ts-jest 发功 范式

  • describe(“大主题”, ()=>{ //此处为 子孙测试代码 }) 用于

    1. 包裹子孙测试代码、隔离其他测试主题
    2. 避免子孙变量污染全局环境
  • test(“小主题”, ()=> { //测试代码 }) 可单独使用 或者使用在 describe 里

  • expect(any).toBe(已知结果) 用于验证返回是否和预期结果一致。

  • jest.fn(()=>void) 用于mock方法。 mock的方法具有 toBeCalled() 是否被调用方法

  • jest.spyOn 用于监视目标

例子

describe("组合", ()=> {
    const fn = jest.fn(()=> "香")
    test("香 还是不 香", () => {
        const result = fn()
        expect(result == "香").toBe(true)
        expect(fn).toBeCalled() 
    })
})
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享