Last active
September 21, 2021 08:15
-
-
Save causztic/ff631e38a25b8f38d497345a4ab4cc68 to your computer and use it in GitHub Desktop.
Jest: Mocking different behaviour in a single file
This file contains hidden or 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
/* | |
* 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