Skip to content

Instantly share code, notes, and snippets.

@GuilhermeCunha
Last active December 15, 2021 12:54
Show Gist options
  • Save GuilhermeCunha/9071f87331c232a0483c44b0687b04d6 to your computer and use it in GitHub Desktop.
Save GuilhermeCunha/9071f87331c232a0483c44b0687b04d6 to your computer and use it in GitHub Desktop.
How to mock function imported directly into the tested file with Jest
import { exampleFunction } from "./file";
export class ExampleClass {
someFunction(){
return exampleFunction()
}
}
export const exampleFunction = () => 'SOMETHING-A'
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