【发布时间】:2020-06-19 05:34:17
【问题描述】:
在我的 TypeScript 项目中设置 jest-test-mock 非常困难。我想知道是否有人能指出我正确的方向?
我有一个看起来像这样的函数:
retrieveData.ts
import fetch from 'cross-fetch';
export async function retrieveData({
endpoint,
configuration,
auth
}: dataInterface): Promise<object> {
try {
console.log('Fetching the requested data... ????')
const settings = configuration
? JSON.parse(render(configuration || '', auth))
: {}
if (settings.body) {
// Ensures the body is stringified in the case of a post request being made.
settings.body = JSON.stringify(settings.body)
}
const response = await fetch(endpoint, settings)
return await response.json()
} catch (error) {
throw new Error(`There was an error fetching from the API: ${error}`)
}
}
我在 fetch.test.ts
中像这样测试它// Enable the mocks
import { enableFetchMocks } from 'jest-fetch-mock'
enableFetchMocks()
import fetchMock from 'jest-fetch-mock';
import {retrieveData, generateExport} from '../src/fetch'
describe('fetch', () => {
describe('retrieveData', () => {
it('should return some data', async () => {
fetchMock.mockResponseOnce(JSON.stringify({ data: '12345' }))
const data = await retrieveData({
endpoint: 'https://example.com'
})
expect(data).toEqual({ data: '12345' })
})
})
})
我遇到的问题是这个库似乎没有接管对fetch 的调用。将完全限定的 URL 放入我的函数将导致返回实际数据。我希望它检索data: '12345' 对象。我哪里错了?
更新:
以下模式在导入import 'cross-fetch/polyfill'; 时有效,但如果我使用import fetch from 'cross-fetch';,则无效。使用第一个 import 语句的问题是它错误我的 linter 说 fetch 没有定义。如果我在 fetch 导入之前控制台日志,它会显示正确的模拟构造函数。我尝试过使用模拟的导入顺序,但仍然存在同样的问题:
import fetchMock, {enableFetchMocks} from 'jest-fetch-mock'
import {retrieveData, generateExport} from '../src/fetch'
enableFetchMocks()
这显然是某种导入订单问题,但我不确定使用 Jest 解决此问题的正确方法。向 eslint 中的全局对象添加 fetch 是否是一个合适的解决方案?
【问题讨论】:
-
这很可能是因为
cross-fetch在你模拟它之前被导入,为了测试是否是这种情况,尝试在创建函数之前和你模拟交叉获取之前添加 console.logs -
在导入显示正确的构造函数之前,在
retrieveData顶部的控制台记录fetch。看这里npmjs.com/package/cross-fetch#install 它说使用import fetch from 'cross-fetch';但使用import 'cross-fetch/polyfill';似乎可以代替。令人困惑... -
用此信息更新了原始帖子。
标签: typescript jestjs jest-fetch-mock