Reactjs 元素消失得太快,Jest无法注意到
我正在测试在获取数据时是否显示加载微调器。因为端点不存在,所以响应是Reactjs 元素消失得太快,Jest无法注意到,reactjs,jestjs,Reactjs,Jestjs,我正在测试在获取数据时是否显示加载微调器。因为端点不存在,所以响应是SyntaxError:Unexpected token
SyntaxError:Unexpected token<在JSON中的位置0
,因为我正在等待的响应上使用JSON()
函数
我该怎么做才能让jest看到加载旋转器在那里?我可以看到它闪烁了一瞬间。。。我能否以某种方式延长getOrganizationInfo
加载周期,使元素可见
这项测试失败了
收到的值必须是HTMLElement或SVGElement。接收的值为空
这是我的简单测试
describe('opened Dialog', () => {
beforeEach(() => {
render(
<DialogProvider>
< StepByStepDialog />
</DialogProvider>,
);
fireEvent.click('button', { name: 'Import Existing' }));
};
it('displays loading spinner on loading', async () => {
const orgNameInput = screen.getByLabelText('Organization Name');
fireEvent.change(orgNameInput, { target: { value: 'ABC123' } });
fireEvent.click('button', { name: 'Continue' });
const loading = screen.queryByText('Validating Organization...');
expect(loading).toBeInTheDocument();
});
});
在放置
organizationUtils.js
文件的同一文件夹中,创建\uuu mocks\uuu
文件夹,其中包含organizationUtils.js
文件。在该文件中,为getOrganizationInfo
函数创建模拟,并在其中调用setTimeout
,例如:
export const getOrganizationInfo = jest.fn(() => {
setTimeout(() => {
Promise.resolve() // here you can put mocked api response if you want
}, 3000)
})
然后在所有导入之前的spec
-文件中,您应该告诉Jest使用mockorganizationUtils.js
文件,如下所示:
jest.mock('../utils/organizationUtils') // put here the right path
it('displays loading spinner on loading', async () => {
jest.useFakeTimers() // we are telling Jest to use fake timers
const orgNameInput = screen.getByLabelText('Organization Name');
fireEvent.change(orgNameInput, { target: { value: 'ABC123' } });
fireEvent.click('button', { name: 'Continue' });
jest.runTimersToTime(2000) // we are telling Jest to ‘jump’ to certain time we want, assuming that on 2nd second the spinner still be shown
const loading = screen.queryByText('Validating Organization...');
expect(loading).toBeInTheDocument();
});
现在该函数已模拟,微调器必须显示3秒钟,但我们可以在测试中控制计时器,您的测试将如下所示:
jest.mock('../utils/organizationUtils') // put here the right path
it('displays loading spinner on loading', async () => {
jest.useFakeTimers() // we are telling Jest to use fake timers
const orgNameInput = screen.getByLabelText('Organization Name');
fireEvent.change(orgNameInput, { target: { value: 'ABC123' } });
fireEvent.click('button', { name: 'Continue' });
jest.runTimersToTime(2000) // we are telling Jest to ‘jump’ to certain time we want, assuming that on 2nd second the spinner still be shown
const loading = screen.queryByText('Validating Organization...');
expect(loading).toBeInTheDocument();
});
顺便说一句,您应该在测试中始终模拟API调用