Last active
December 16, 2020 03:36
-
-
Save Kalimaha/97ed847ca872a594f191b6d02977441b to your computer and use it in GitHub Desktop.
Jest/TS: Mock a dependency of the entity under test
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 { eggs, eggsAsync } from "../src/eggs"; | |
import { spam, spamAsync } from "../src/spam"; | |
jest.mock("../src/spam"); | |
describe("Synchronous Implementation", () => { | |
describe("non-mocked", () => { | |
beforeEach(() => { (spam as jest.Mock).mockImplementationOnce((a: number) => 10 * a) }); | |
it("performs some calculations", () => { | |
expect(eggs(3)).toEqual(72); | |
}); | |
}); | |
describe("mocked", () => { | |
beforeEach(() => { (spam as jest.Mock).mockImplementationOnce(() => 100) }); | |
it("performs some calculations", () => { | |
expect(eggs(3)).toEqual(142); | |
}); | |
}); | |
}); | |
describe("Asynchronous Implementation", () => { | |
describe("non-mocked", () => { | |
beforeEach(() => { (spamAsync as jest.Mock).mockResolvedValue(30) }); | |
it("performs some asynchronous calculations", async() => { | |
expect(eggsAsync(3)).resolves.toEqual(72); | |
}); | |
}); | |
describe("mocked", () => { | |
beforeEach(() => { (spamAsync as jest.Mock).mockResolvedValue(100) }); | |
it("performs some asynchronous calculations", async() => { | |
expect(eggsAsync(3)).resolves.toEqual(142); | |
}); | |
}); | |
}); |
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 { spam, spamAsync } from "./spam"; | |
export const eggs = (a: number) => 42 + spam(a); | |
export const eggsAsync = async (a: number) => | |
spamAsync(a).then(res => res + 42); |
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 spam = (a: number): number => 10 * a; | |
export const spamAsync = async (a: number): Promise<number> => spam(a); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
jest.mock("../src/spam")
has to be at the very top (or at least before everything) and once used, all the tests will use the mock, not the real implementation.