繁体   English   中英

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

实用程序/ index.js

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

->utils/ __mocks__ /index.js

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

开玩笑的配置文件

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

jestSetup.js

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

开玩笑的配置文件

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

jestSetup.js

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

或者用模拟创建一个文件

模拟.js

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

jestSetup.js

  import './mocks.js'

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

jest.unmock('../utils')

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM