All quizzesMedium
Mocks, Spies & Integration — Series 2
Preview — 3 of 10 questions
What does mockReturnValue({ success: true }) configure, and what does this test verify?
javascript
function processOrder(paymentGateway, amount) {
const result = paymentGateway.charge(amount);
return result.success ? 'Order confirmed' : 'Payment failed';
}
test('confirms order on successful payment', () => {
const paymentGateway = { charge: jest.fn() };
paymentGateway.charge.mockReturnValue({ success: true });
expect(processOrder(paymentGateway, 100)).toBe('Order confirmed');
expect(paymentGateway.charge).toHaveBeenCalledWith(100);
});AmockReturnValue only works for the first call to the mock; every subsequent call returns undefined.
BmockReturnValue replaces the mock function entirely with a real network request to a payment gateway.
CmockReturnValue configures what the mock function returns whenever it's called; the test passes, confirming processOrder correctly interprets a successful charge and that charge was called with 100.
DThe test fails, since jest.fn() cannot be combined with .mockReturnValue().
What does mockResolvedValue({...}) do differently from mockReturnValue({...})?
javascript
async function getUserName(api, id) {
const user = await api.fetchUser(id);
return user.name;
}
test('returns the user name from the API', async () => {
const api = { fetchUser: jest.fn() };
api.fetchUser.mockResolvedValue({ id: 1, name: 'Alice' });
const name = await getUserName(api, 1);
expect(name).toBe('Alice');
});AmockResolvedValue makes the mock function synchronous, removing the need for await in the test.
BmockResolvedValue makes the mock return a Promise that resolves to the given value — the correct choice for mocking an async function, since calling code will await the result expecting a Promise-like value.
CmockResolvedValue and mockReturnValue are exactly identical; there is no difference.
DmockResolvedValue can only be used with jest.spyOn, never with jest.fn().
What is logged?
javascript
function logEvent(logger, eventName, payload) {
logger.record(eventName, payload);
}
test('records call arguments correctly', () => {
const logger = { record: jest.fn() };
logEvent(logger, 'signup', { userId: 42 });
logEvent(logger, 'login', { userId: 42 });
console.log(logger.record.mock.calls.length);
console.log(logger.record.mock.calls[0]);
console.log(logger.record.mock.calls[1][0]);
});A2, 'signup', { userId: 42 }
B1, ['signup', { userId: 42 }], 'login'
C2, ['signup', { userId: 42 }], { userId: 42 }
D2, ['signup', { userId: 42 }], 'login'
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.