Man*_*anu 4 javascript api unit-testing jestjs fetch-mock
我所有的GET请求都在通过,但POST请求失败。当我fetch-mock从7.3.0to7.3.1或later更新时会发生这种情况。
控制台警告 Unmatched POST to url
错误 fetch-mock: No fallback response defined for POST to url
http.js
export const get = (url) => {
const options = {
method: 'GET',
credentials: 'same-origin'
};
return fetch(url, options).then(handleJsonResponse);
};
export const post = (url, body) => {
const headers = {
'content-type': 'application/json',
'pragma': 'no-cache',
'cache-control': 'no-cache'
};
return fetch(url, {
credentials: 'same-origin',
method: 'POST',
cache: 'no-cache',
body: JSON.stringify(body),
headers
}).then(handleJsonResponse);
};
Run Code Online (Sandbox Code Playgroud)
http.spec.js
const url = '/path/to/url'
describe('get', () => {
it('makes a GET request', async () => {
fetchMock.mock({
name: 'route',
matcher: url,
method: 'GET',
credentials: 'same-origin',
response: {
status: 200,
body: []
}
});
const response = await get(url);
expect(fetchMock.called()).toEqual(true);
expect(fetchMock.calls().length).toEqual(1);
expect(fetchMock.calls('route').length).toEqual(1);
expect(response).toEqual([]);
});
});
describe('post', () => {
const requestBody = {request: 'request'};
it('makes a POST request', async () => {
fetchMock.mock({
name: 'route',
matcher: url,
method: 'POST',
credentials: 'same-origin',
cache: 'no-cache',
body: JSON.stringify(requestBody),
headers: {
'content-type': 'application/json',
'pragma': 'no-cache',
'cache-control': 'no-cache'
},
response: {
status: 200,
body: []
}
});
const response = await post(url, requestBody);
expect(fetchMock.called()).toEqual(true);
expect(fetchMock.calls().length).toEqual(1);
expect(fetchMock.calls('route').length).toEqual(1);
expect(fetchMock.lastOptions().headers).toEqual({
'content-type': 'application/json',
'pragma': 'no-cache',
'cache-control': 'no-cache'
});
expect(response).toEqual([]);
});
});
Run Code Online (Sandbox Code Playgroud)
关于是什么原因造成的任何想法?有没有办法获得更有意义的日志来帮助调试?
我宁愿不去尝试nock或jest-fetch-mock的替代路径。
好吧,经过数小时的深入研究图书馆本身,我发现了问题所在。
在我的代码(和上面的代码段)中,我将 body字符串化JSON.stringify(body)。图书馆generate-matcher.js正在解析它JSON.parse(body),然后比较两者 - 导致失败的点。我现在只是将它作为原始对象发送。
如果将来有其他人最终来到这里,我也会遇到同样的错误fetch-mock unmatched get。
我看到对此问题的回复提交给 fetch-mock,这促使我仔细检查我的预期值和模拟值。
事实证明,我的问题与所描述的错误完全相同,其中我期望的模拟路由与正在调用的实际路由由于拼写错误而不匹配。
| 归档时间: |
|
| 查看次数: |
5396 次 |
| 最近记录: |