Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Mocha、Sinon和Chai在回调中测试两个http调用_Node.js_Mocha.js_Sinon - Fatal编程技术网

Node.js Mocha、Sinon和Chai在回调中测试两个http调用

Node.js Mocha、Sinon和Chai在回调中测试两个http调用,node.js,mocha.js,sinon,Node.js,Mocha.js,Sinon,我正在与Chai Mocha和Sinon进行一些非常简单的测试。我想知道您将如何测试在回调内部调用的http方法。如果可以,请给我指出正确的方向,努力在上面找到任何东西,我知道你可以做到,只是不知道怎么做。我的代码如下: index.js index.spec.js const Index = require('../index') const http = require('http') const { stub, fake, assert } = require('sinon') const

我正在与Chai Mocha和Sinon进行一些非常简单的测试。我想知道您将如何测试在回调内部调用的http方法。如果可以,请给我指出正确的方向,努力在上面找到任何东西,我知道你可以做到,只是不知道怎么做。我的代码如下:

index.js

index.spec.js

const Index = require('../index')
const http = require('http')
const { stub, fake, assert } = require('sinon')
const { expect } = require('chai')

let httpSpy;

beforeEach(function () {
  a = new Index()
  httpSpy = stub(http, 'get')
})

describe('When the get method is invoked', function () {
  beforeEach(function () {
    a.get('http://www.google.co.uk')
  })

  it('should make a call to the http service with passed in uri', function () {
    assert.calledOnce(httpSpy) // This really should be called twice (Part I am struggling with)
    assert.calledWith(httpSpy, 'http://www.google.co.uk')
    // I want to test instead that the httpSpy was called twice as, inside the get method, when the first http get resolves, another one gets fired off also
  })
})
有两个问题

首先,我们无法判断
Index.get()
方法执行何时结束(它不接受回调,也不返回承诺,也不标记为异步等)

这种方法的使用极不方便。例如:如果我们想先执行
Index.get()
,然后在无法执行之后立即执行一些操作

为了解决这个问题,我们可以添加一个回调作为
Index.get
的最后一个参数

第二个问题是
http.get
方法是如何存根的:

httpSpy = stub(http, 'get')
这行的基本意思是:用空函数替换
http.get
。如果在内部传递回调,则该伪函数不会抛出,但它不会调用它

这就是为什么只调用一次
http.get
。它只是忽略传递的回调,其中应第二次调用
http.get

为了解决这个问题,我们可以使用
stub.yields()
方法让sinon知道传递给stub的最后一个参数是回调(sinon需要调用它)。您可以在中找到该方法

以下是一个工作示例,请参见我的评论:

类索引{
//在这里添加了回调
获取(uri,回调){
http.get(uri,()=>{
http.get('/',()=>{
//将要返回的任何数据传递到此处
回调(null,{});
})
})
}
}
让httpSpy;
在每个之前(()=>{
a=新索引()
//现在sinon希望回调作为最后一个参数,并调用它
httpSpy=stub(http,'get').yields();
})
descriple('调用get方法时',()=>{
常量uri=http://www.google.co.uk';
//现在,我们正在等待执行在任何断言之前结束
每次之前(完成=>{
a、 get(uri,done);
});
它('应该使用传入的uri调用http服务',()=>{
assert.calledTwice(httpSpy);
assert.match(httpSpy.getCall(0.args[0],uri));
assert.match(httpSpy.getCall(1.args[0],“/”);
});

})
我只看到一个get调用。get方法调用http.get,然后在第一个http get方法的回调中调用另一个http get方法谢谢!那天晚上晚些时候我确实明白了这一点,但你的解释帮助我理解了为什么我会答应这个请求
get(uri) { ... }
httpSpy = stub(http, 'get')