Dar*_*ryn 11 unit-testing axios 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' }
]
});
Run Code Online (Sandbox Code Playgroud)
我如何判断是否调用了'/ users'?
我正在寻找类似于你在Jest中可以做的事情:
expect(mockFunc).toHaveBeenCalledTimes(1)
Run Code Online (Sandbox Code Playgroud)
我意识到我可以在使用函数回复时使用一些自定义逻辑,并设置一个局部变量来指示是否已经发出请求.我只是想知道是否有更清洁的方法来做到这一点.
axios-mock-adapter似乎没有内置此功能,但是,如果您使用的是jest,则可以使用jest.spyOn。
对于上面的例子
let spy = jest.spyOn(axios, "get");
//run http request here
expect(spy).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)
注意:根据您使用的内容,您可能必须将您的Expect语句包装在setTimeout(function,0)中,以使其正常工作
根据https://github.com/ctimmerm/axios-mock-adapter,有一个用于验证请求调用的开箱即用功能:
expect(mock.history.post.length).toBe(1); // times called
expect(mock.history.post[0].data).toBe(JSON.stringify({ foo: "bar" })); // posted object
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3317 次 |
| 最近记录: |