首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试中的模拟远程HTTP响应

测试中的模拟远程HTTP响应
EN

Stack Overflow用户
提问于 2017-11-07 19:27:28
回答 1查看 1.1K关注 0票数 1

我试图编写一个测试,根据从API收到的响应来检查我的应用程序的行为。要做到这一点,我试图使响应我提出的请求有我需要的配置。

一个例子是检查我的应用程序在登录后重定向到主页。我需要响应为HTTP 200,并具有API键的任何值。

我正在使用axios发出请求

目前,我尝试了以下库,但没有成功

  • 艾灸
  • axios-模拟适配器
  • 诺克

有人有过模拟远程HTTP请求及其响应的经验吗?

编辑:如果有帮助的话,我正在用摩卡和柴做测试。

代码语言:javascript
复制
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 }]

EN

回答 1

Stack Overflow用户

发布于 2018-02-19 17:58:56

我的例子大多取自艾灸医生

首先,在测试中导入所需的库。之后,您将处理在beforeEachafterEach钩子中创建和销毁模拟axios服务器。然后,将一个sinon.spy()传递到axios的get请求,您想要监视它。

这个get请求将被most模拟,您可以通过moxios.wait(() => { moxios.request.mostRecent(); });wait()方法中访问它,您可以在最近的请求上设置您想要的响应。

之后,就像使用axios时一样,您将使用then()函数来获得响应。在then()中,您可以为特定的响应创建测试。当您完成您的规范时,请调用done();关闭请求并移动规范。

代码语言:javascript
复制
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();
      })
    })
  })
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47165984

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档