我是项目测试部分的新手。
我的个人项目遇到问题。我使用“ superagent”从Api获取信息,现在我想为其编写测试。但是我不能使用酶示例中使用的“ 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-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;
感谢你们的所有帮助。