Last active
December 15, 2021 12:54
-
-
Save GuilhermeCunha/9071f87331c232a0483c44b0687b04d6 to your computer and use it in GitHub Desktop.
How to mock function imported directly into the tested file with Jest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { exampleFunction } from "./file"; | |
export class ExampleClass { | |
someFunction(){ | |
return exampleFunction() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const exampleFunction = () => 'SOMETHING-A' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as fileExports from "./file"; | |
import * as ExampleClass from "./file-to-test"; | |
const exampleClass = new ExampleClass() | |
describe('Some describe', () => { | |
it('must mock value', (done) => { | |
const newReturnValue = 'ANOTHER-THING'; | |
jest.spyOn(fileExports, 'exampleFunction').mockImplementation(() => newReturnValue); | |
expect(exampleClass.someFunction()).toBe(newReturnValue); // This works correctly. | |
done(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment