Skip to content

Instantly share code, notes, and snippets.

@truseed
Forked from rickhanlonii/mock_implementation.js
Created November 4, 2019 22:20
Show Gist options
  • Save truseed/7794becda21425e4efbe181266b71a53 to your computer and use it in GitHub Desktop.
Save truseed/7794becda21425e4efbe181266b71a53 to your computer and use it in GitHub Desktop.
Mock Implementation
test("mock implementation", () => {
const mock = jest.fn(() => "bar");
expect(mock("foo")).toBe("bar");
expect(mock).toHaveBeenCalledWith("foo");
});
test("also mock implementation", () => {
const mock = jest.fn().mockImplementation(() => "bar");
expect(mock("foo")).toBe("bar");
expect(mock).toHaveBeenCalledWith("foo");
});
test("mock implementation one time", () => {
const mock = jest.fn().mockImplementationOnce(() => "bar");
expect(mock("foo")).toBe("bar");
expect(mock).toHaveBeenCalledWith("foo");
expect(mock("baz")).toBe(undefined);
expect(mock).toHaveBeenCalledWith("baz");
});
test("mock return value", () => {
const mock = jest.fn();
mock.mockReturnValue("bar");
expect(mock("foo")).toBe("bar");
expect(mock).toHaveBeenCalledWith("foo");
});
test("mock promise resolution", () => {
const mock = jest.fn();
mock.mockResolvedValue("bar");
expect(mock("foo")).resolves.toBe("bar");
expect(mock).toHaveBeenCalledWith("foo");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment