xxxxxxxxxx
test("mock.calls", () => {
const mockFn = jest.fn();
mockFn(1, 2);
expect(mockFn.mock.calls).toEqual([[1, 2]]);
});
xxxxxxxxxx
// index.test.js
const getFirstAlbumTitle = require('./index');
const axios = require('axios');
jest.mock('axios');
it('returns the title of the first album', async () => {
axios.get.mockResolvedValue({
data: [
{
userId: 1,
id: 1,
title: 'My First Album'
},
{
userId: 1,
id: 2,
title: 'Album: The Sequel'
}
]
});
const title = await getFirstAlbumTitle();
expect(title).toEqual('My First Album');
});
xxxxxxxxxx
There are a few different ways to approach it.
You can mock only foo using jest.spyOn and something like mockImplementation:
import { MyClass } from './MyClass';
import * as FooFactory from './somewhere/FooFactory';
describe('test MyClass', () => {
test('construct', () => {
const mock = jest.spyOn(FooFactory, 'foo'); // spy on foo
mock.mockImplementation((arg: string) => 'TEST'); // replace implementation
const c = new MyClass('test');
expect(c).toBeDefined();
expect(c.getState()).toEqual('TEST'); // SUCCESS
mock.mockRestore(); // restore original implementation
});
});
Similarly, you can auto-mock FooFactory with jest.mock, then provide an implementation for foo:
import { MyClass } from './MyClass';
import * as FooFactory from './somewhere/FooFactory';
jest.mock('./somewhere/FooFactory'); // auto-mock FooFactory
describe('test MyClass', () => {
test('construct', () => {
const mockFooFactory = FooFactory as jest.Mocked<typeof FooFactory>; // get correct type for mocked FooFactory
mockFooFactory.foo.mockImplementation(() => 'TEST'); // provide implementation for foo
const c = new MyClass('test');
expect(c).toBeDefined();
expect(c.getState()).toEqual('TEST'); // SUCCESS
});
});
You can also mock FooFactory using a module factory passed to jest.mock:
import { MyClass } from './MyClass';
jest.mock('./somewhere/FooFactory', () => ({
foo: () => 'TEST'
}));
describe('test MyClass', () => {
test('construct', () => {
const c = new MyClass('test');
expect(c).toBeDefined();
expect(c.getState()).toEqual('TEST'); // SUCCESS
});
});
And finally, if you plan to use the same mock across multiple test files you can mock the user module by creating a mock at ./somewhere/__mocks__/FooFactory.ts:
export function foo(arg: string) {
return 'TEST';
}
then call jest.mock('./somewhere/FooFactory'); to use the mock in the test:
import { MyClass } from './MyClass';
jest.mock('./somewhere/FooFactory'); // use the mock
describe('test MyClass', () => {
test('construct', () => {
const c = new MyClass('test');
expect(c).toBeDefined();
expect(c.getState()).toEqual('TEST'); // SUCCESS
});
});
xxxxxxxxxx
test("mockName", () => {
const mockFn = jest.fn().mockName("mockedFunction");
mockFn(); // comment me
expect(mockFn).toHaveBeenCalled();
});
xxxxxxxxxx
import Foo from './Foo';
import Bar from './Bar';
jest.mock('./Bar');
describe('Foo', () => {
it('should return correct foo', () => {
// As Bar is already mocked,
// we just need to cast it to jest.Mock (for TypeScript) and mock whatever you want
(Bar.prototype.runBar as jest.Mock).mockReturnValue('Mocked bar');
const foo = new Foo();
expect(foo.runFoo()).toBe('real foo : Mocked bar');
});
});
xxxxxxxxxx
const bodyToAssertAgainst = {};
globals.request.post = jest.fn().mockImplementation((obj, cb) => {
cb(null, bodyToAssertAgainst);
});
xxxxxxxxxx
const myMockFn = jest
.fn()
.mockImplementationOnce(cb => cb(null, true))
.mockImplementationOnce(cb => cb(null, false));
myMockFn((err, val) => console.log(val));
// > true
myMockFn((err, val) => console.log(val));
// > false
xxxxxxxxxx
/*
The Mock Function
The goal for mocking is to replace something we don’t control with something
we do, so it’s important that what we replace it with has all the features
we need.
The Mock Function provides features to:
1. Capture calls
2. Set return values
3. Change the implementation
The simplest way to create a Mock Function instance is with jest.fn()
*/
test("returns undefined by default", () => {
const mock = jest.fn();
let result = mock("foo");
expect(result).toBeUndefined();
expect(mock).toHaveBeenCalled();
expect(mock).toHaveBeenCalledTimes(1);
expect(mock).toHaveBeenCalledWith("foo");
});
xxxxxxxxxx
test("mock.instances", () => {
const mockFn = jest.fn();
const a = new mockFn();
const b = new mockFn();
mockFn.mock.instances[0] === a;
mockFn.mock.instances[1] === b;
});