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

我想要这样的东西:

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中添加模拟定义

jest.config.js

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

jestSetup.js

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

或使用模拟创建文件

mocks.js

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

jestSetup.js

  import './mocks.js'

如果您不想在特定测试中使用mock,可以调用:

jest.unmock('../utils')

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

相关文章