我在使stubRequest正常工作时遇到问题。这是我的代码:
it('should stub my request', (done) => {
moxios.stubRequest('/authenticate', {
status: 200
})
//here a call to /authenticate is being made
SessionService.login('foo', 'bar')
moxios.wait(() => {
expect(something).toHaveHappened()
done()
})
})
这很好:
it('should stub my request', (done) => {
SessionService.login('foo', 'bar')
moxios.wait(async () => {
let request = moxios.requests.mostRecent()
await request.respondWith({
status: 200
})
expect(something).toHaveHappened()
done()
})
})
第二个方法虽然是最后一个调用,但我真的很想能够显式地存根某些请求。
我正在和Vue一起玩Jest。
答案 0 :(得分:0)
如果您向我们展示该服务,那就太好了。服务呼叫必须在moxios等待功能内部,而外部必须仅是axios呼叫。我已经粘贴了一个简化的stubRequest
describe('Fetch a product action', () => {
let onFulfilled;
let onRejected;
beforeEach(() => {
moxios.install();
store = mockStore({});
onFulfilled = sinon.spy();
onRejected = sinon.spy();
});
afterEach(() => {
moxios.uninstall();
});
it('can fetch the product successfully', done => {
const API_URL = `http://localhost:3000/products/`;
moxios.stubRequest(API_URL, {
status: 200,
response: mockDataSingleProduct
});
axios.get(API_URL, mockDataSingleProduct).then(onFulfilled);
const expectedActions = [
{
type: ACTION.FETCH_PRODUCT,
payload: mockDataSingleProduct
}
];
moxios.wait(function() {
const response = onFulfilled.getCall(0).args[0];
expect(onFulfilled.calledOnce).toBe(true);
expect(response.status).toBe(200);
expect(response.data).toEqual(mockDataSingleProduct);
return store.dispatch(fetchProduct(mockDataSingleProduct.id))
.then(() => {
var actions = store.getActions();
expect(actions.length).toBe(1);
expect(actions[0].type).toBe(ACTION.FETCH_PRODUCT);
expect(actions[0].payload).not.toBe(null || undefined);
expect(actions[0].payload).toEqual(mockDataSingleProduct);
expect(actions).toEqual(expectedActions);
done();
});
});
});
})
答案 1 :(得分:0)
我带着类似的目标来到这里,最终使用可能对其他人有帮助的不同方法解决了这个问题:
moxios.requests
有一个方法 .get()
(source code) 可以让您根据 URL 从 moxios.requests
获取特定请求。这样,如果您有多个请求,您的测试不需要以特定顺序发生请求即可工作。
这是它的样子:
moxios.wait(() => {
// Grab a specific API request based on the URL
const request = moxios.requests.get('get', 'endpoint/to/stub');
// Stub the response with whatever you would like
request.respondWith(yourStubbedResponseHere)
.then(() => {
// Your assertions go here
done();
});
});
注意:
方法 .get()
的名称有点误导。它可以处理不同类型的 HTTP 请求。类型作为第一个参数传递,如:moxios.requests.get(requestType, url)