在我的玩笑-测试-模拟项目中设置TypeScript非常困难。我想知道是否有人能为我指明正确的方向?
我有一个像这样的函数:
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';,则不会。使用第一个导入语句的问题是,它错误地使用了我的linter,它说没有定义fetch。如果我在fetch导入之前控制台日志,它将显示正确的模拟构造函数。我试过使用模拟程序的导入顺序,但它仍然存在相同的问题:
import fetchMock, {enableFetchMocks} from 'jest-fetch-mock'
import {retrieveData, generateExport} from '../src/fetch'
enableFetchMocks()这显然是某种进口订单问题,但我不确定用Jest解决这个问题的正确方法。在eslint中向全局对象添加fetch是解决这个问题的适当解决方案吗?
发布于 2020-03-06 14:53:10
你能试试这段代码吗。
describe('retrieveData', () => {
it('should return some data', () => {
fetchMock.mockResponseOnce(JSON.stringify({ data: '12345' }))
retrieveData({
endpoint: 'https://example.com'
}).then(res => {
expect(res).toEqual({ data: '12345' })
})
})
})https://stackoverflow.com/questions/60564794
复制相似问题