Ts-jest is a well-known unit testing framework.

Pure TS project integration approach

  1. First add the following ingredients to package.json
  "scripts": {
    "test": "jest --passWithNoTests"
  },
 "devDependencies": {
    "typescript": "*",
    "ts-jest": "*"
  }
Copy the code
  1. Then add the jest. Config. js file to the project root directory with the following formula:
module.exports = { preset: "ts-jest", roots: [ "<rootDir>/__tests__" ], transform: { "^.+\\.(t|j)sx? $": "ts-jest", }, transformIgnorePatterns: [ "node_modules" ] };Copy the code
  1. Then, in the tests folder at the root of the project, add the test file ending with.test.ts.

  2. After the test file is written, use YARN test to harvest ✔️ or ×.

Ts-jest power paradigm

  • Describe (” big topic “, ()=>{// here is descendant test code}) used

    1. Wraps descendant test code and isolates other test topics
    2. Avoid polluting the global environment with posterity variables
  • Test (” small topic “, ()=> {// test code}) can be used alone or in describe

  • Expect (any).tobe (known result) is used to verify that the return matches the expected result.

  • Jest.fn (()=>void) is used for mock methods. The mock method has toBeCalled() whether the method is called

  • Jest. SpyOn is used to monitor the target

example

Describe (" combination ", () = > {const fn = jest, fn (() = > "sweet") test (" sweet or not sweet." () => {const result = fn() expect(result == "").tobe (true) expect(fn).tobecalled ()})})Copy the code