Krz*_*zos 6 javascript typescript jestjs
我对这段代码有疑问:
\n\nimport useCountry from './useCountry';\nimport { renderHook } from '@testing-library/react-hooks';\nimport { enableFetchMocks } from 'jest-fetch-mock';\nenableFetchMocks();\n\nit('should make proper api call', async () => {\n const resultCountries = {\n PL: 'Poland',\n CA: 'Canada',\n };\n\n jest.spyOn(global, 'fetch').mockImplementation(() =>\n Promise.resolve({\n json: () => Promise.resolve(resultCountries),\n } as Response),\n );\n\n const expected = [\n { code: 'PL', name: 'Poland' },\n { code: 'CA', name: 'Canada' },\n ];\n\n const { result, waitForNextUpdate } = renderHook(() => useCountry());\n await waitForNextUpdate();\n\n expect(fetch).toHaveBeenCalled();\n expect(result.current).toEqual(expected);\n});\nRun Code Online (Sandbox Code Playgroud)\n\n删除时as Response,我收到此 Typescript 警告:
\n\n\nTS2345:类型参数 '() => Promise<{ json: () => Promise<{ PL: string; CA:字符串;}>; }>' 不可分配给类型为“(input?: string | Request | undefined, init?: RequestInit | undefined) => Promise”的参数。\xc2\xa0\xc2\xa0Type 'Promise<{ json: () => Promise<{ PL: string; CA:字符串;}>; }>' 不可分配给类型“Promise”。\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0Type '{ json: () => Promise<{ PL: string; CA:字符串;}>; 'Response' 类型缺少以下属性: headers、ok、redirected、status 以及其他 11 个属性。
\n
我想问如何正确地模拟fetch,因为这as Response感觉是一种不好的做法。
小智 0
我在模拟函数时遇到了这个问题fetch,只需在.test.tsx.
//app.test.tsx
global.fetch = jest.fn(async () =>
Promise.resolve({ json: async () => Promise.resolve({ id: 0 }) })
) as jest.Mock;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5056 次 |
| 最近记录: |