Nock无法同时运行多个测试 [英] Nock not working for multiple tests running together
问题描述
我正在使用nock
库对我的http调用进行存根.
不同的测试文件require('nock')
并进行存根.
如果每个测试单独运行,则所有测试都通过.
但是,如果所有测试一起运行,则以后的测试会失败,因为而不是nock发出了实际的请求.
I am using nock
library to stub my http calls.
Different test files require('nock')
and do their stubbing.
If each test is run separately, all is passing.
But if all tests run together, later tests fail because instead of nock, actual request was made.
例如,考虑以下代码片段.它具有两个不同的
describe
块,每个块都有多个测试用例.如果我运行此文件node node_modules/mocha/bin/_mocha test.js
,则前两个测试将通过,但第三个测试(在不同的describe
块中)将失败,因为它实际上会调用
Consider below code snippet for example. It has two different
describe
blocks, each with multiple test cases. If I run this filenode node_modules/mocha/bin/_mocha test.js
then the first two tests will pass, but the third test (in differentdescribe
block) would fail because it would actually call the
/* 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.
Funny thing is, if I do console.log(nock.activeMocks())
, then I can see that nock did register the URL to mock.
[ 'POST http://google.com:80/path3' ]
推荐答案
如本 Github Issue ,nock.restore()
会删除http拦截器本身.在调用nock.restore()
后运行nock.isActive()
时,它将返回false
.因此,您需要先运行nock.activate()
,然后再使用它.
As discussed in this Github Issue, nock.restore()
removes the http interceptor itself. When you run nock.isActive()
after calling nock.restore()
it will return false
. So you need to run nock.activate()
before using it again.
删除nock.restore()
.
在测试中具有此before()
方法.
before(function (done) {
if (!nock.isActive()) nock.activate()
done()
})
这篇关于Nock无法同时运行多个测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!