【问题标题】:Jest - one function mocks file for multiple test filesJest - 一个函数模拟多个测试文件的文件
【发布时间】:2021-03-03 22:06:53
【问题描述】:

我想要这样的东西:

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);
})

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

【问题讨论】:

  • 您好,您可以在函数内部定义模拟,然后在需要的地方调用该函数。
  • @lissettdm 你能举个例子吗?
  • 可重复使用的模拟是 __mocks__ 的用途。你试过了吗?

标签: javascript reactjs jestjs react-testing-library


【解决方案1】:

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

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

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'

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

jest.unmock('../utils')

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

【讨论】:

  • 我想更进一步,我可以在同一个测试目录中使用另外两个模拟吗?例如,两个文件使用来自一个文件的模拟,另外两个文件使用来自第二个文件的模拟。我在你附加到这个答案的网页上没有找到它,这个答案只能为所有测试提供一个端点实现
  • 能否附上你有这个场景的链接,以便我更清楚地理解它?
猜你喜欢
  • 2018-08-27
  • 2019-09-19
  • 2017-11-11
  • 1970-01-01
  • 2018-03-20
  • 1970-01-01
  • 2015-06-20
  • 2020-02-13
  • 2014-10-21
相关资源
最近更新 更多