reactjs - 如何在我的反应项目中使用“酶”和“笑话”测试使用“超级代理”的异步操作?
问题描述
我是项目测试部分的新手。
我的个人项目有问题。我使用“superagent”从 Api 获取信息,现在我想为它编写测试。但我不能使用 Enzyme 示例中使用的 'fetch-mock' 包。
这是我的动作文件。
// getRecommendedProductsActions.js
import request from 'superagent';
export const getRecommendedProducts = () => (dispatch) => {
dispatch(fetchProducts());
return request
.get(URL_PRODUCT_BASE)
.set('Content-Type', 'application/json')
.then(res => dispatch(receiveProducts(res.body)))
.catch(err => dispatch(receiveFailure(err)));
};
这是我的测试文件。
// test/getRecommendedProducts.test.js
import configureMockStore from 'redux-mock-store';
import fetchMock from 'fetch-mock';
import thunk from 'redux-thunk';
import { getRecommendedProducts } from '../../src/actions/products';
describe('async actions', () => {
afterEach(() => {
fetchMock.reset();
fetchMock.restore();
});
it('creates RECEIVE_PRODUCTS when fetching products has been done', () => {
fetchMock
.get('/products', {
body: httpBody,
headers: { 'content-type': 'application/json' },
});
const expectedActions = successResponse;
const store = mockStore();
return store.dispatch(getRecommendedProducts())
.then(() => expect(store.getActions()).toEqual(expectedActions));
});
而且我发现“superagent”不是基于 fetch 的,“fetch-mock”不起作用。我也找到了一个__mocks__/superagent.js
文件。
// mock for superagent - __mocks__/superagent.js
let mockDelay;
let mockError;
let mockResponse = {
status() {
return 200;
},
ok() {
return true;
},
body: {
walla: true,
},
get: jest.fn(),
toError: jest.fn(),
};
const Request = {
post() {
return this;
},
get() {
return this;
},
send() {
return this;
},
query() {
return this;
},
field() {
return this;
},
set() {
return this;
},
accept() {
return this;
},
timeout() {
return this;
},
end: jest.fn().mockImplementation(function (callback) {
if (mockDelay) {
this.delayTimer = setTimeout(callback, 0, mockError, mockResponse);
return;
}
callback(mockError, mockResponse);
}),
// expose helper methods for tests to set
__setMockDelay(boolValue) {
mockDelay = boolValue;
},
__setMockResponse(mockRes) {
mockResponse = mockRes;
},
__setMockError(mockErr) {
mockError = mockErr;
},
};
module.exports = Request;
感谢你们的所有帮助。
解决方案
推荐阅读
- ios - 线程 1:致命错误:索引超出范围。没有快速从数组中获取值,控制台显示它们不是空数组
- angular - 没有组件的Angular2路由
- assembly - 如何修复此代码中的异常“错误:操作码和操作数的无效组合”?
- javascript - 路由器链接到带有参数的路径
- java - 卸载以前版本的 APK 并删除更新时的所有数据
- swift - 如何在 macOS 的保存对话框中显示替代文件格式
- list - Haskell-我如何遍历和比较数组/列表
- python - 比较字典的值并返回匹配值的计数
- perl - 通过 ls() 使用 Perl::SFTP::Foreign 计数文件
- typescript - Webpack 似乎忽略了我的打字稿加载器