Javascript 如何使用fetch测试api调用
关于单元测试Javascript 如何使用fetch测试api调用,javascript,unit-testing,reactjs,mocking,fetch,Javascript,Unit Testing,Reactjs,Mocking,Fetch,关于单元测试fetch的正确方法是什么,我找不到确切的答案。我正在使用createreact应用程序build。到目前为止,这是我发现的用户建议使用nock&node fetch的最近一次。我在这里看到了图书馆的一些发展:但它的建设失败了,这让我很紧张 目标是通过jest 根据经验,是否有人对使用fetch api测试请求的最佳方法有任何建议?您应该使用fetch mock,就像您链接到测试新的fetch api调用一样 构建失败的事实对您来说毫无意义。这只是为了让开发人员在承诺使用github
fetch
的正确方法是什么,我找不到确切的答案。我正在使用createreact应用程序
build。到目前为止,这是我发现的用户建议使用nock
&node fetch
的最近一次。我在这里看到了图书馆的一些发展:但它的建设失败了,这让我很紧张
目标是通过jest
根据经验,是否有人对使用fetch api测试请求的最佳方法有任何建议?您应该使用
fetch mock
,就像您链接到测试新的fetch api调用一样
构建失败的事实对您来说毫无意义。这只是为了让开发人员在承诺使用github进行持续开发时知道。当您使用npmi--save dev fetch mock
时,它将下载github作者专门发布的(希望是)工作版本,而不是失败的构建
我的项目中的redux thunk操作示例:
import expect from 'expect';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';
import * as actions from './formActions';
const mockStore = configureStore([thunk]);
const store = mockStore({});
const body = {
email: 'test@gmail.com',
};
describe('registerFormActions', () => {
let calledActions;
beforeEach(() => {
store.clearActions();
calledActions = store.getActions();
});
afterEach(() => {
fetchMock.reset().restore();
});
it('should post form', () => {
fetchMock.postOnce('/account/register', body);
store.dispatch(actions.submit()).then(() => {
expect(fetchMock.called('/account/register')).toBe(true);
});
});
});
export const submit = formData => dispatch =>
fetch('/account/register', {
method: 'post',
body: formData,
credentials: 'same-origin',
}).then((response) => {
if (response.ok) {
// Do something cool
}
});
嗯,很高兴听到有人用过它。我会继续推进的。。谢谢,我害怕掉进兔子洞。没问题。下次我只想看一下文档,如果它看起来像您需要的,那么就没有理由不使用它,特别是对于非生产代码的单元测试。