nightwatch.js测试中的模拟后端 [英] Mock backend in nightwatch.js tests

查看:176
本文介绍了nightwatch.js测试中的模拟后端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Vue.js应用程序中,我正在使用夜视仪来测试我的应用程序.我有以下规格:

In my Vue.js app I'm using nightwatch to test my app. I have the following spec:

module.exports = {
  'wrong email or password': function (browser) {
    const devServer = browser.globals.devServerURL
    var nock = require('nock');

    var couchdb = nock('http://localhost:3000/')
                    .get('api/v1/login')
                    .reply(401, {
                      error: 'dupa'
                     });

    browser
      .url(devServer + '/login')
      .setValue('input[type=email]', 'email@example.com')
      .setValue('input[type=password]', 'password')
      .click('.login')
      .assert.containsText('#app', 'Niepoprawny email lub hasło.')
      .end()
  }
}

在我的测试中,我尝试使用 https://github.com/node-nock/诺克.不幸的是,这不会嘲笑任何请求.我在做什么错了?

In my test I'm trying to use https://github.com/node-nock/nock. But unfortunately this not mocks any requests. What I'm doing wrong?

推荐答案

Nock替换了运行它的浏览器环境中的HTTP机制. 由于您正在测试中运行它,而没有在浏览器中运行它,因此浏览器环境不变.

Nock replaces the HTTP mechanism in the browser environment in which it is run. Since you're running it in your test, which isn't running in the browser, the browser environment is unchanged.

您可以执行几项操作,但这取决于您要实现的目标:

There are several things you could do, but that depends on what you're trying to achieve:

  1. 您可以编写一个假服务器,让它在3000端口监听并以您喜欢的任何方式答复.
  2. 您可以将应用程序配置为根据配置使用其他机制,并使其在测试中加载Nock策略".
  3. 如果您要检查UI的其他测试,则可以用执行实际请求的功能的单元测试和集成测试来代替此测试.

要编写伪造品,您只需要一个简单的服务器即可返回您想要的答案.这是express.js的示例:

To write a fake, you just need a simple server that returns the answer you want. Here's an example with express.js:

const express = require('express')
const app = express()

app.get('/api/v1/login', function (req, res) {
  res.send('Some response')
})

app.listen(3000, function () {
  console.log('server listening on port 3000')
})

这篇关于nightwatch.js测试中的模拟后端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆