我在让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。
发布于 2018-08-23 22:00:40
如果你给我们看一下这项服务就好了。服务调用必须在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();
});
});
});
})发布于 2021-02-26 01:42:05
我带着类似的目标来到这里,并最终用一种可能对其他人有帮助的不同方法解决了这个问题:
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)
https://stackoverflow.com/questions/51983221
复制相似问题