[Tip] jest Tips
keywords: test
, test-driven development
, TDD
, tips
更多 mock function 的範例
mock custom hooks
方式一
import { render, screen } from '@testing-library/react';
import App from './App';
/**
* STEP 1: import and mock custom hooks
**/
import useTodos from './components/TodoApp/useTodos';
jest.mock('./components/TodoApp/useTodos');
test('renders learn react link', async () => {
// STEP 2: implement the mock return value
useTodos.mockImplementation(() => ({
todos: [
{
userId: 1,
id: 1,
title: 'foobar',
completed: true,
},
],
}));
render(<App />);
const header = await screen.findByRole('heading', { name: 'Tasks' });
const todos = await screen.findByTestId('todos');
expect(header).toBeInTheDocument();
expect(todos.children.length).toBe(200);
});
方式二
import { render, screen } from '@testing-library/react';
import App from './App';
/**
* STEP 1: import and mock custom hooks
**/
import useTodos from './components/TodoApp/useTodos';
/**
* STEP 2: mock customized hook with return value
**/
jest.mock('./components/TodoApp/useTodos', {
_esModule: true,
useTodos: () => ({
todos: [
{
userId: 1,
id: 1,
title: 'foobar',
completed: true,
},
],
}),
});
test('renders learn react link', async () => {
render(<App />);
const header = await screen.findByRole('heading', { name: 'Tasks' });
const todos = await screen.findByTestId('todos');
expect(header).toBeInTheDocument();
expect(todos.children.length).toBe(200);
});
mock SWR
方式一
import { render, screen } from '@testing-library/react';
import App from './App';
/**
* STEP 1: import and mock the useSWR
**/
import useSWR from 'swr';
jest.mock('swr');
test('renders learn react link', async () => {
// STEP 2: implement the mock return value of useSWR
useSWR.mockImplementation(() => ({
data: [
{
userId: 1,
id: 1,
title: 'foobar',
completed: true,
},
],
error: null,
isValidating: false,
mutate: null,
}));
render(<App />);
const header = await screen.findByRole('heading', { name: 'Tasks' });
const todos = await screen.findByTestId('todos');
expect(header).toBeInTheDocument();
expect(todos.children.length).toBe(200);
});