Javascript Jest/Ezyme:如何处理在另一个异步函数中调用的异步函数?
我试图运行Jest/Ezyme异步测试获取温度,我遇到了一些不熟悉的地方。如果我定义经度和纬度并注释掉getUserCoordinates,我就能通过测试。问题是,我如何编写测试来允许/模拟fetchTemperatures中的异步函数返回值 ~此外,如果代码的编写方式有任何其他问题,请告诉我,我正在尝试对js环境进行预热 fetch.js fetch.test.jsJavascript Jest/Ezyme:如何处理在另一个异步函数中调用的异步函数?,javascript,reactjs,jestjs,enzyme,Javascript,Reactjs,Jestjs,Enzyme,我试图运行Jest/Ezyme异步测试获取温度,我遇到了一些不熟悉的地方。如果我定义经度和纬度并注释掉getUserCoordinates,我就能通过测试。问题是,我如何编写测试来允许/模拟fetchTemperatures中的异步函数返回值 ~此外,如果代码的编写方式有任何其他问题,请告诉我,我正在尝试对js环境进行预热 fetch.js fetch.test.js 模拟getUserCoordinates非常简单,您有几个不同的选项: 您可以使用jest.mock,它获取包含getUserC
模拟getUserCoordinates非常简单,您有几个不同的选项: 您可以使用jest.mock,它获取包含getUserCoordinates的模块的路径并截取它,从您提供的回调返回模拟值: //这假定“getUserCoordinates”是一个命名的导出。 //如果它是默认的导出,只需要回调返回jest.fn。。。 jest.mock'./get user coordinates.js',=>{ getUserCoordinates:jest.fn.mockResolvedValue{lat:0,long:0}; }; 您还可以使用import*as,它允许您在不使用jest.mock的情况下模拟导入: //您可以随意命名'api' 从“/获取用户坐标”导入*作为api; api.getUserCoordinates=jest.fn.mockResolvedValue{lat:0,long:0}; 还有一件事:在第三次到最后一次测试中,您应该确保返回响应。然后…,否则您的测试将在等待进入前通过。然后阻止: //返回承诺会使测试等待到 //`.then`在完成之前执行。 返回响应。结果=>{ 预期结果。ToeQualmock反应; };
谢谢你的帮助,我可能不得不退后一步,阅读更多的文档,因为我仍然没有得到它。我不确定在哪里插入该模拟,以便它在后续测试中真正发挥作用。到目前为止,,当我尝试将该命令插入BeforeAll块时,我得到一个错误::Timeout-异步回调未在jest.setTimeout.Timeout指定的5000ms超时内调用。Timeout-异步回调未在jest.setTimeout.error指定的5000ms超时内调用:。很抱歉,您无法使其工作!下面是jest文档中的示例,也许这会有所帮助:。。。此外,您可以尝试将beforeach更改为beforeach。。。
export const fetchTemperatures = async (format = 'weather', source = 'openWeather') => {
// for 5-day-forecast set format arg to "forecast"
try {
let response;
const { longitude, latitude } = await getUserCoordinates();
//! the nested async above is preventing me from running the tests...
// let longitude = 100;
// let latitude = 100;
if (source === 'openWeather') {
response = await fetch(
`${openWeatherURL}/${format}?APPID=${process.env
.REACT_APP_OW_API_KEY}&lat=${latitude}&lon=${longitude}&units=imperial`
);
} else if (source === 'darkSky') {
response = await fetch(
`${darkSkyURL}${process.env
.REACT_APP_DS_API_KEY}/${latitude},${longitude}?exclude=[currently,minutely,hourly,flags]`
);
} else {
//! is this getting hit? -- not sure
throw new Error("Enter a valid source string. Ex: 'openWeather' or 'darkSky'");
}
return await response.json();
} catch (error) {
throw new Error('Fetch failed');
}
};
describe('fetchTemperatures()', () => {
let mockResponse = { data: 'Weather related data.' };
let response;
beforeAll(() => {
window.fetch = jest.fn().mockImplementation(() => {
return Promise.resolve({
ok: true,
json: () => Promise.resolve(mockResponse)
});
});
//! Number of calls: 0 === FIGURE OUT NESTED ASYNC IN SOURCE
response = fetchTemperatures();
});
// argument-based routes
it('args=default, should call fetch with the correct url', () => {
fetchTemperatures();
expect(window.fetch).toHaveBeenCalledWith(
`${openWeatherURL}/weather?APPID=${process.env
.REACT_APP_OW_API_KEY}&lat=${latitude}&lon=${longitude}&units=imperial`
);
});
it('args="weather", should call fetch with the correct url', () => {
fetchTemperatures('forecast');
expect(window.fetch).toHaveBeenCalledWith(
`${openWeatherURL}/weather?APPID=${process.env
.REACT_APP_OW_API_KEY}&lat=${latitude}&lon=${longitude}&units=imperial`
);
});
it('args="weather", "darkSky", should call fetch with the correct url', () => {
fetchTemperatures('weather', 'darkSky');
expect(window.fetch).toHaveBeenCalledWith(
`${darkSkyURL}${process.env
.REACT_APP_DS_API_KEY}/${latitude},${longitude}?exclude=[currently,minutely,hourly,flags]`
);
});
// success
it('Success::Promise Resolve: should return with the current weather', () => {
response.then((results) => {
expect(results).toEqual(mockResponse);
});
});
// failure - success but response not ok
it('Failure::Response !ok: should return an error', () => {
window.fetch = jest.fn().mockImplementation(() => {
return Promise.resolve({
ok: false
});
});
expect(fetchTemperatures()).rejects.toEqual(Error('Fetch failed'));
});
// failure - reject
it('Failure::Promise Rejects', () => {
window.fetch = jest.fn().mockImplementation(() => {
return Promise.reject(Error('Fetch failed'));
});
expect(fetchTemperatures()).rejects.toEqual(Error('Fetch failed'));
});
});