node.js – Nock不能同时运行多个测试

我正在使用nock库来存根我的http调用.

不同的测试文件需要(‘nock’)并进行存根.

如果每个测试分别运行,则全部通过.

但是如果所有测试一起运行,后来的测试就会失败,因为而不是nock,实际的请求.

Consider below code snippet for example. It has two different describe blocks, each with multiple test cases. If I run this file node node_modules/mocha/bin/_mocha test.js then the first two tests will pass, but the third test (in different describe block) would fail because it would actually call the google URL.

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

有趣的是,如果我执行console.log(nock.activeMocks()),那么我可以看到nock确实将URL注册为mock.

[ 'POST http://google.com:80/path3' ]

最佳答案 正如在这个
Github Issue中讨论的那样,nock.restore()删除了http拦截器本身.在调用nock.restore()之后运行nock.isActive()时,它将返回false.所以你需要在再次使用之前运行nock.activate().

解决方案1:

删除nock.restore().

解决方案2:

在测试中使用此before()方法.

  before(function (done) {
    if (!nock.isActive()) nock.activate()
    done()
  })
点赞