Nock无法同时运行多个测试

Ras*_*ash 5 node.js nock

我正在使用nock库来存根http调用。不同的测试文件require('nock')并进行存根处理。如果每个测试单独运行,则所有测试都通过。但是,如果所有测试一起运行,则以后的测试将失败,因为发出了实际的请求而不是nock。

例如,考虑以下代码片段。它具有两个不同的describe块,每个块具有多个测试用例。如果我运行此文件,node node_modules/mocha/bin/_mocha test.js则前两个测试将通过,但第三个测试(在不同的describe块中)将失败,因为它实际上会调用该googleURL。

/* eslint-env mocha */

let expect = require('chai').expect
let nock = require('nock')
let request = require('request')

let url = 'http://localhost:7295'

describe('Test A', function () {
  after(function () {
    nock.restore()
    nock.cleanAll()
  })

  it('test 1', function (done) {
    nock(url)
      .post('/path1')
      .reply(200, 'input_stream1')

    request.post(url + '/path1', function (error, response, body) {
      expect(body).to.equal('input_stream1')
      done()
    })
  })

  it('test 2', function (done) {
    nock(url)
      .post('/path2')
      .reply(200, 'input_stream2')

    request.post(url + '/path2', function (error, response, body) {
      expect(body).to.equal('input_stream2')
      done()
    })
  })
})

// TESTS IN THIS BLOCK WOULD FAIL!!!
describe('Test B', function () {
  after(function () {
    nock.restore()
    nock.cleanAll()
  })

  it('test 3', function (done) {
    nock('http://google.com')
      .post('/path3')
      .reply(200, 'input_stream3')

    request.post('http://google.com' + '/path3', function (error, response, body) {
      expect(body).to.equal('input_stream3')
      done()
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

有趣的是,如果我这样做了console.log(nock.activeMocks()),那么我可以看到nock确实注册了要模拟的URL。

[ 'POST http://google.com:80/path3' ]
Run Code Online (Sandbox Code Playgroud)

Ras*_*ash 5

正如此Github Issue中所讨论的,nock.restore()删除了 http 拦截器本身。当你nock.isActive()调用后运行nock.restore()它会返回false。所以你需要运行nock.activate()所以再次使用之前

解决方案一:

消除nock.restore()。

解决方案2:

在你的测试中使用这个before()方法。

  before(function (done) {
    if (!nock.isActive()) nock.activate()
    done()
  })
Run Code Online (Sandbox Code Playgroud)