有一个很棒的打字本取钩,我想嘲笑它。这里:https://usehooks-ts.com/react-hook/use-fetch
我的应用程序基本上是这样的:
export default function App() {
const { data, error } = useFetch<InterfaceOfTheResponse>(FETCH_URL)
if (error) return <p>Error</p>
if (!data) return <p>Loading...</p>
return (
<div className="App">
<h1>Welcome</h1>
//data.map... etc
</div>
)
}我的测试看起来如下:
import { mockData } from "../__mocks__/useFetch"
const mockConfig = {
data: mockData,
error: false,
}
jest.mock("../../customHooks/useFetch", () => {
return {
useFetch: () => mockConfig
}
})
describe("Main page functionality", () => {
test("Renders main page, Welcome", async () => {
const { findByText } = render(<App />)
const WELCOME = await findByText(/Welcome/)
expect(WELCOME).toBeInTheDocument()
})
})我试过几种方法来嘲弄它,这是我认为它最应该起作用的方法,但它(显然)不起作用。它说,(在测试screen.debug()中)显示" error“if语句,甚至当我从组件中省略if错误检查时,”数据“仍未定义。那我做错什么了?
发布于 2022-10-21 03:56:25
不要嘲笑useFetch钩子的实现,您可能会破坏它的功能。相反,我们应该模拟浏览器的获取 API及其响应。
例如。
App.tsx
import React from 'react';
import { useFetch } from 'usehooks-ts'
const FETCH_URL = 'http://localhost:3000/api';
export default function App() {
const { data, error } = useFetch<any[]>(FETCH_URL)
console.log(data, error);
if (error) return <p>Error</p>
if (!data) return <p>Loading...</p>
return (
<div className="App">
<h1>Welcome</h1>
{data.map(d => <div key={d}>{d}</div>)}
</div>
)
}App.test.tsx
import { render, screen } from "@testing-library/react";
import '@testing-library/jest-dom';
import React from "react";
import App from './App';
describe('74144869', () => {
test('should pass', async () => {
const mData = [1, 2]
const mResponse = {
ok: true,
json: jest.fn().mockResolvedValue(mData)
}
global.fetch = jest.fn().mockResolvedValue(mResponse as unknown as Response);
render(<App />);
expect(await screen.findByText(1)).toBeInTheDocument();
})
});测试结果:
PASS stackoverflow/74144869/App.test.tsx (11.11 s)
74144869
✓ should pass (58 ms)
console.log
undefined undefined
at App (stackoverflow/74144869/App.tsx:7:11)
console.log
undefined undefined
at App (stackoverflow/74144869/App.tsx:7:11)
console.log
[ 1, 2 ] undefined
at App (stackoverflow/74144869/App.tsx:7:11)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 91.67 | 75 | 100 | 100 |
App.tsx | 91.67 | 75 | 100 | 100 | 9
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 11.797 s, estimated 12 s包版本:
"usehooks-ts": "^2.9.1",
"@testing-library/react": "^11.2.7",
"@testing-library/jest-dom": "^5.11.6",https://stackoverflow.com/questions/74144869
复制相似问题