Skip to content

Instantly share code, notes, and snippets.

@causztic
Last active September 21, 2021 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save causztic/ff631e38a25b8f38d497345a4ab4cc68 to your computer and use it in GitHub Desktop.
Save causztic/ff631e38a25b8f38d497345a4ab4cc68 to your computer and use it in GitHub Desktop.
Jest: Mocking different behaviour in a single file
/*
* Say that I want to test a component with an imported function that has different behaviours.
*
* e.g.
* import { authenticate } from "~/some/module"
* authenticate: (...) => boolean
*
*/
jest.mock("~/some/module");
const AuthenticationService = require("~/some/module");
describe("when authentication is invalid", () => {
beforeEach(() => {
AuthenticationService.authenticate = jest.fn().mockResolvedValue(false);
});
test("the flow should fail", async () => {
const result = await someHOC("username", "wrong-password");
expect(result).toEqual(401);
});
});
describe("when authentication is valid", () => {
beforeEach(() => {
AuthenticationService.authenticate = jest.fn().mockResolvedValue(true);
});
test("the flow should pass", () => {
const result = someHOC("username", "correct-password");
expect(result).toEqual(200);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment