我试图编写一个测试,根据从API收到的响应来检查我的应用程序的行为。要做到这一点,我试图使响应我提出的请求有我需要的配置。
一个例子是检查我的应用程序在登录后重定向到主页。我需要响应为HTTP 200,并具有API键的任何值。
我正在使用axios发出请求
目前,我尝试了以下库,但没有成功
有人有过模拟远程HTTP请求及其响应的经验吗?
编辑:如果有帮助的话,我正在用摩卡和柴做测试。
it('Does stuff', function () {
moxios.stubRequest('/auth/get_api_key', {
status: 200,
responseText: 'hello'
})
return this.app.client.setValue('[name="username"]', 'testing').then(() => {
return this.app.client.setValue('[name="password"]', 'testing').then(() => {
return this.app.client.submitForm('#login-form').then(() => {
return this.app.client.getRenderProcessLogs().then(function (logs) {
console.log(logs)
})
})
})
})
})上面的代码是我用来查看请求是否通过并输出以下内容的代码
[{ level:‘严厉’,消息:'键/键 -未能加载资源: net::ERR_CONNECTION_REFUSED',源:‘网络’,时间戳: 1510082077495 }]
发布于 2018-02-19 17:58:56
我的例子大多取自艾灸医生。
首先,在测试中导入所需的库。之后,您将处理在beforeEach和afterEach钩子中创建和销毁模拟axios服务器。然后,将一个sinon.spy()传递到axios的get请求,您想要监视它。
这个get请求将被most模拟,您可以通过moxios.wait(() => { moxios.request.mostRecent(); });在wait()方法中访问它,您可以在最近的请求上设置您想要的响应。
之后,就像使用axios时一样,您将使用then()函数来获得响应。在then()中,您可以为特定的响应创建测试。当您完成您的规范时,请调用done();关闭请求并移动规范。
import axios from 'axios';
import moxios from 'moxios';
import sinon from 'sinon';
import { equal } from 'assert'; //use the testing framework of your choice
beforeEach(() => {
moxios.install();
});
afterEach(() => {
moxios.uninstall();
});
it('Does stuff', (done) => {
moxios.withMock(() => {
let onFulfilled = sinon.spy();
axios.get('/auth/get_api_key').then(onFulfilled);
moxios.wait(() => {
let request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: {
apiKey: 1234567890
}
}).then((res) => {
equal(onFulfilled.called, true);
equal(res.status, 200);
equal(res.response.apiKey, 1234567890);
done();
})
})
})
});https://stackoverflow.com/questions/47165984
复制相似问题