当我在浏览器中测试该组件时,它工作正常。单击按钮时,文本变为'bye'。几秒钟后,当数据提取完成时,它又变回'hi'。但在Jest中,它根本无法检测到'bye'文本。
我得到的错误是“TestingLibraryElementError:找不到具有以下文本的元素:/再见/我”
Test.jsx
import React, { useState } from 'react';
export const Test = () => {
const [isLeaving, setIsLeaving] = useState(false);
const handler = async () => {
setIsLeaving(true);
const response = await fetch('https://api.jikan.moe/v4/anime/1/full');
const data = await response.json();
console.log({ data });
setIsLeaving(false);
};
return (
<div>
<p>{!isLeaving ? 'hi' : 'bye'}</p>
<button onClick={handler}>click me</button>
</div>
);
};
Test.spec.jsx
import {render,screen,waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Test } from './Test';
import '@testing-library/jest-dom';
describe('Test component test', () => {
global.fetch = jest.fn(() =>
Promise.resolve({
json: () =>
Promise.resolve({
data: {
id: 1,
attributes: {
titles: { en: 'Fullmetal Alchemist' },
synopsis: 'After losine.'
}
}
})
})
);
it('should show "bye" text before showing "hi" text when data fetching is don', async () => {
const user = userEvent.setup();
render(<Test />);
expect(screen.getByText(/hi/i)).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: /click me/i }));
expect(screen.getByText(/bye/i)).toBeInTheDocument();
await waitFor(() => {
expect(screen.getByText(/hi/i)).toBeInTheDocument();
});
});
});
1条答案
按热度按时间u1ehiz5o1#
为
res.json()
方法创建延迟承诺。请在用户单击按钮后解决此问题。index.tsx
:index.test.tsx
:试验结果: