您如何验证使用axios-mock-adapter发出的请求? [英] How do you verify that a request was made with axios-mock-adapter?
问题描述
我正在使用 https://github.com/ctimmerm/axios-mock-adapter
我想知道如何验证被测系统实际上调用了一个端点.
在此示例中:
var axios = require('axios');
var MockAdapter = require('axios-mock-adapter');
// This sets the mock adapter on the default instance
var mock = new MockAdapter(axios);
// Mock any GET request to /users
// arguments for reply are (status, data, headers)
mock.onGet('/users').reply(200, {
users: [
{ id: 1, name: 'John Smith' }
]
});
我怎么知道是否调用了'/users'?
我正在寻找类似于Jest的功能:
expect(mockFunc).toHaveBeenCalledTimes(1)
我意识到在使用函数进行回复并设置指示是否已发出请求的局部变量时,可以使用一些自定义逻辑.我只是想知道是否有更清洁的方法.
axios-mock-adapter似乎没有内置此功能,但是,如果您使用的是jest,则可以使用jest.spyOn.>
在上面的示例中
let spy = jest.spyOn(axios, "get");
//run http request here
expect(spy).toHaveBeenCalled();
注意:根据所使用的内容,可能必须将您的Expect语句包装在setTimeout(function,0)中,以使其正常工作
I am using https://github.com/ctimmerm/axios-mock-adapter
I would like to know how can I verify that an endpoint was actually called by the system under test.
In this example:
var axios = require('axios');
var MockAdapter = require('axios-mock-adapter');
// This sets the mock adapter on the default instance
var mock = new MockAdapter(axios);
// Mock any GET request to /users
// arguments for reply are (status, data, headers)
mock.onGet('/users').reply(200, {
users: [
{ id: 1, name: 'John Smith' }
]
});
How could I tell if a get on '/users' was called?
I am looking for something similar to what you can do in Jest:
expect(mockFunc).toHaveBeenCalledTimes(1)
I realise I can use some custom logic when using a function to reply, and setting a local variable indicating if the request has been made. I was just wondering if there was a cleaner way of doing this.
axios-mock-adapter does not appear to have this functionality built in to it, however if you are using jest, you can use jest.spyOn.
For your example above
let spy = jest.spyOn(axios, "get");
//run http request here
expect(spy).toHaveBeenCalled();
Note: depending on what you are using, you may have to wrap your expect statement in setTimeout(function, 0) for it to work properly
这篇关于您如何验证使用axios-mock-adapter发出的请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!