Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
106
rated 0 times [  112] [ 6]  / answers: 1 / hits: 6441  / 4 Years ago, fri, november 20, 2020, 12:00:00

I want to have something like this:


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

Is it possible to have one file where mocked functions are implemented, and then import them in multiple tests files?


More From » reactjs

 Answers
12

There are some alternative to accomplish this:



  1. Add __mocks__ directory inside utils folder. See 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. Add mock definition directly in jestSetup.js


jest.config.js


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

jestSetup.js


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

or create a file with mocks


mocks.js


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

jestSetup.js


  import './mocks.js'

If you don't want to use mocks on specific test, you can call:


jest.unmock('../utils')

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


[#2265] Monday, November 16, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ellisw

Total Points: 625
Total Questions: 92
Total Answers: 88

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
ellisw questions
Mon, Aug 23, 21, 00:00, 3 Years ago
Sat, Jun 20, 20, 00:00, 4 Years ago
Tue, Apr 21, 20, 00:00, 4 Years ago
;