Mocking with Jest and Typescript

Published

Use the ts-jest/utils mocked function to assist in testing:

import { mocked } from "ts-jest/utils";
import someLib, { SomeReturnType } from "some-lib";

// Mock the library
jest.mock("some-library");

// Create a typed, mocked instance of the lib under test.
const mockedLib = mocked(someLib, true);

describe("CognitoService", () => {
	beforeEach(() => {
		// Reset mocks for each test
		mockedLib.someMethod.mockReset();
	});

	test(".someMethod", async () => {
		// Setup
		const expected = { foo: "bar" };
		mockedSetup.someMethod.mockReturnValueOnce(expected as SomeReturnType);

		// Run
		someLib.someMethod();

		// Assert
		expect(mockedLib.someMethod).toBeCalledWith(expected);
	});
});

Like this post?
Why don't you let me know on Twitter: @danawoodman