Javascript 使用定制钩子提供的数据测试React组件
我已创建此自定义挂钩以获取数据:Javascript 使用定制钩子提供的数据测试React组件,javascript,reactjs,jestjs,enzyme,Javascript,Reactjs,Jestjs,Enzyme,我已创建此自定义挂钩以获取数据: const useSuggestionsApi = () => { const [data, setData] = useState({ suggestions: [] }); const [url, setUrl] = useState(''); const [loading, setLoading] = useState(false); const [error, setError] = useState(false); use
const useSuggestionsApi = () => {
const [data, setData] = useState({ suggestions: [] });
const [url, setUrl] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
useEffect(() => {
const fetchData = () => {
setError(false);
setLoading(true);
if(url) {
fetch(url).then((res) => {
if (res.status !== 200) {
console.error(`It seems there was an problem fetching the result. Status Code: ${res.status}`)
return;
}
res.json().then((fetchedData) => {
setData(fetchedData)
})
}).catch(() => {
setError(true)
})
setLoading(false);
};
}
fetchData();
}, [url]);
return [{ data, loading, error }, setUrl];
}
export default useSuggestionsApi;
此组件中使用它来呈现响应(建议
)
我是测试React组件的新手,非常感谢您的帮助 这是有效的:
jest.mock('../hooks/useSuggestionsApi', () => {
return jest.fn(() => [{data: mockResponse}, jest.fn()]
)
})
describe('SearchSuggestions', () => {
const wrapper = shallow(<SearchSuggestions query="jas"/>)
it('correct amount of list-items gets rendered according to fetched data', () => {
expect(wrapper.find('.search-suggestions__list').children()).toHaveLength(mockResponse.suggestions.length);
});
})
jest.mock(“../hooks/useSuggestionsApi”,()=>{
返回jest.fn(()=>[{data:mockResponse},jest.fn()]
)
})
描述('搜索建议',()=>{
常量包装器=浅()
它('根据获取的数据呈现正确数量的列表项',()=>{
expect(wrapper.find('.search-suggestions\uu list').children()).toHaveLength(mockResponse.suggestions.length);
});
})
describe('SearchSuggestions', () => {
const wrapper = shallow(<SearchSuggestions/>)
it('test if correct amount of list-item elements are rendered', () => {
jest.mock("../hooks/useSuggestionsApi", () => ({
useSuggestionsApi: () => mockResponse
}));
expect(wrapper.find('.search-suggestions__list').children()).toHaveLength(mockResponse.data.suggestions.length);
});
})
jest.mock('../hooks/useSuggestionsApi', () => {
return jest.fn(() => [{data: mockResponse}, jest.fn()]
)
})
describe('SearchSuggestions', () => {
const wrapper = shallow(<SearchSuggestions query="jas"/>)
it('correct amount of list-items gets rendered according to fetched data', () => {
expect(wrapper.find('.search-suggestions__list').children()).toHaveLength(mockResponse.suggestions.length);
});
})