Skip to main content

[Tip] jest Tips

keywords: test, test-driven development, TDD, tips#

測試 AJAX 的 API#

The only 3 steps you need to mock an API call in Jest @ dev.to

// 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');
});
Last updated on