Skip to content

Instantly share code, notes, and snippets.

@Kalimaha
Last active December 16, 2020 03:36
Show Gist options
  • Save Kalimaha/97ed847ca872a594f191b6d02977441b to your computer and use it in GitHub Desktop.
Save Kalimaha/97ed847ca872a594f191b6d02977441b to your computer and use it in GitHub Desktop.
Jest/TS: Mock a dependency of the entity under test
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);
});
});
});
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);
export const spam = (a: number): number => 10 * a;
export const spamAsync = async (a: number): Promise<number> => spam(a);
@Kalimaha
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment