Mock backend in nightwatch.js tests

心已入冬 提交于 2019-12-21 21:53:45

问题


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()
  }
}

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?


回答1:


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. You could write a fake server and have it listen at port 3000 and answer any way you like.
  2. You could configure your application to use a different mechanism according to configuration, and have it load a Nock 'strategy' in the test.
  3. If you have other tests checking the UI, you could replace this test with unit tests and integration tests for the functions that do the actual requests.

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')
})


来源:https://stackoverflow.com/questions/46183354/mock-backend-in-nightwatch-js-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!