use*_*893 2 javascript jasmine
我正在寻找测试嵌套获取。到目前为止,我可以测试第一次获取的结果,但无法访问另一个。我尝试将下一个 fetch 调用嵌套在第一个调用中,但这似乎不起作用。第二个 SpyOn 函数调用会创建一个茉莉花错误,表示我不能为同一函数设置多个间谍。
茉莉花测试
let response = new Response(
JSON.stringify({
test: "test",
})
);
// creating a fetch spy
spyOn(window, "fetch").and.returnValue(Promise.resolve(response));
// make call to fetch
callFirstFetch().then((result) => {
expect(window.fetch).toHaveBeenCalledWith("/test");
spyOn(window, "fetch").and.returnValue(Promise.resolve(response));
done();
});
Run Code Online (Sandbox Code Playgroud)
嵌套的获取代码看起来像
function firstFetch(() => {
return fetch("/test")
.then(response => {
response.json();
return secondFetch();
})
});
function secondFetch(() => {
return fetch("/test2")
.then(response => {
response.json();
console.log('done');
})
});
firstFetch();
Run Code Online (Sandbox Code Playgroud)
小智 6
这是模拟 fetch api 调用的方法:
const okResponse = new Response(JSON.stringify({}), { status: 200, statusText: 'OK', });
spyOn(window, 'fetch').and.resolveTo(okResponse);
Run Code Online (Sandbox Code Playgroud)
然后像这样测试它:
expect(window.fetch).toHaveBeenCalledWith(requestUrl, options);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4938 次 |
| 最近记录: |