// 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');
});
const bodyToAssertAgainst = {};
globals.request.post = jest.fn().mockImplementation((obj, cb) => {
cb(null, bodyToAssertAgainst);
});
/*
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");
});
test("mock.calls", () => {
const mockFn = jest.fn();
mockFn(1, 2);
expect(mockFn.mock.calls).toEqual([[1, 2]]);
});