Jest - 一个函数模拟多个测试文件的文件

Jest - one function mocks file for multiple test files

我想要这样的东西:

mockFunctions.ts

jest.mock('../utils', () => {
  return {
     getNumbers: () => [1,2,3]
  }
})

__tests__/test1.ts

---import from mockFunctions---
...
it('After adding another number array has more elements', () => {
   const numbers = <get these numbers using mock function>
   expect([...numbers, 11]).toHaveLength(4);
})

__tests__/test2.ts

---import from mockFunctions---
...
it('After removing a number, array has less elements', () => {
   const numbers = <get these numbers using mock function>
   expect(numbers.filter(x => x>1)).toHaveLength(2);
})

是否可以在一个文件中实现模拟功能,然后将它们导入多个测试文件?

有一些替代方法可以做到这一点:

  1. 在 utils 文件夹中添加 __mocks__ 目录。参见 https://jestjs.io/docs/en/manual-mocks

utils/index.js

export const  getNumbers= () => [1, 2, 3, 4, 5];

->utils/__mocks__/index.js

export const  getNumbers= () => [3, 4];

jest.config.js

{ 
   "setupFilesAfterEnv": [
      "<rootDir>/jestSetup.js"
    ]
}

jestSetup.js

jest.mock("../utils"); // will apply to all tests
  1. 直接在jestSetup.js
  2. 中添加模拟定义

jest.config.js

{ 
   "setupFilesAfterEnv": [
      "<rootDir>/jestSetup.js"
    ]
}

jestSetup.js

  jest.mock("../utils", () => ({
     getNumbers: () => [3, 4]
  }));

或使用 mocks 创建一个文件

mocks.js

  jest.mock("../utils", () => ({
     getNumbers: () => [3, 4]
  }));

jestSetup.js

  import './mocks.js'

如果你不想在特定测试中使用模拟,你可以调用:

jest.unmock('../utils')

参见:https://jestjs.io/docs/en/jest-object#jestunmockmodulename