所以基本上我尝试使用一个我用假数据做的模拟来测试一些组件。这一切都很好,但是当我尝试使用“findAllByRole”方法时,它只返回了一个空对象,并抛出一个错误,告诉我所有角色为“listitem”的项都不存在。
主部分测试js
import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import MainSection from './MainSection.js';
import { getItems } from '../../Database/Database.js';
import axios from 'axios';
import mockProducts from '../../Database/mockProducts.js';
jest.mock('axios');
beforeEach(() => {
render(<MainSection />);
});
test('Check if renders all the 20 items in the MainSection', async () => {
axios.get.mockResolvedValue({
data: mockProducts,
});
await getItems();
const allBoxes = screen.findAllByRole('listitem');
expect(allBoxes).toHaveLength(20);
});
主要章节. js
import React, { useState, useEffect } from 'react';
import SearchBar from './SearchBar/SearchBar.js';
import FiltersBox from './FiltersBox/FiltersBox.js';
import { getItems } from '../../Database/Database.js';
import './MainSection.css';
function MainSection() {
const [items, setItems] = useState([]);
useEffect(() => {
getItems().then(res => setItems(res));
}, []);
return (
<section>
<article className='items_container-main'>
<div className='items_container' role='list'>
items.map(item => (
<div
className='item_box'
style={{ backgroundImage: `url(${item.image})` }}
key={item.id}
role='listitem'>
<div className='item_box-data_container'>
<div className='item_box-data_container-price_star'>
<div className='item_box-price'>${item.price}</div>
<div className='item_box-title'>{item.title}</div>
</div>
</div>
))}
</div>
</article>
</section>
);
}
export default MainSection;
数据库. js
错误
我的所有文件(如果需要)
我认为这就是错误的原因,因为我需要让测试使用带有虚假数据的模拟作为API响应数据,但我不知道如何才能做到这一点...
1条答案
按热度按时间xdnvmnnf1#
jest.mock('axios')
模拟整个axios
模块,您可以只模拟axios.get()
方法。axios.get()
之后呈现组件。await screen.findAllByRole('listitem')
到waiting for appearanceMainSection.jsx
:MainSection.test.jsx
:试验结果: