有一個很棒的 typescript fetch hook 我想模擬它。在這里: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() 中)“錯誤”if 陳述句,即使我從組件中省略了 if 錯誤檢查,“資料”也是未定義的。那么我做錯了什么?
uj5u.com熱心網友回復:
不要模擬useFetch鉤子的實作,你可能會破壞它的功能。相反,我們應該模擬瀏覽器的fetch 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://www.uj5u.com/qukuanlian/520982.html
上一篇:在Go中測驗GRPC流發送功能
