【问题标题】:get callback arguments from sinon.spy inside promise javascript从 promise javascript 中的 sinon.spy 获取回调参数
【发布时间】:2018-01-13 08:12:32
【问题描述】:

我正在使用 mocha 和 sinon 运行测试,以从 HTTP 请求的承诺范围内获取回调值,但由于承诺的异步性质,它不起作用。这是因为当 sinon.spy 检查回调时,它已经消失并变为空或未定义。这是测试代码:

 it('should issue GET /messages ', function() {
  server.respondWith('GET', `${apiUrl}/messages?counter=0`, JSON.stringify([]));
  let callback = sinon.spy();
  Babble.getMessages(0, callback);
  server.respond();
  sinon.assert.calledWith(callback, []);
});

和承诺:

function requestPoll(props) {
    return new Promise(function(resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.open(props.method, props.action);
            xhr.timeout = 500; // time in milliseconds
            if (props.method === 'post' ) {
                    xhr.setRequestHeader('Content-Type', 'application/json');
            }
            xhr.addEventListener('load', function(e) {
                    resolve(e.target.responseText);
            });

            xhr.send(JSON.stringify(props.data));


    });
}

以及我试图从 sinon.spy 上获取回调的调用

getMessages: function(counter, callback){

            requestPoll({

                            method: "GET",
                            action: "http://localhost:9090/messages?counter="+counter

            }).then(function(result){

                    callback(result);
            });


        }

sinon.spy 说它没有任何参数(由于异步功能)。我试图寻找一种方法来获取范围之外的结果并将其放在回调中。但我发现这是不可能的。也尝试过resolve和promise return,但没有成功。

我怎样才能使这个单元测试通过?

编辑:
这是我的尝试:

getMessages: function(counter, callback){

            var res;
            res = httpRequestAsync("GET",'',"http://localhost:9097/messages?counter=",counter);

            console.log(res);
            if(res!="")
                    callback( JSON.parse(res) );                      
        }

我把请求放在一个单独的函数中:

function httpRequestAsync(method,data,theUrl,counter)
    {

            return requestPoll({

                    method: method,
                    action: theUrl+counter,
                    data: data

            }).then(JSON.parse);

    }

它返回res 作为承诺,在它的原型里面有我需要的承诺值。

我如何才能获得那里承诺的价值?

【问题讨论】:

  • getMessages返回一个正确的promise而不是回调,这将导致更好和更容易测试的代码。
  • 你能告诉我吗?我尝试了几次返回承诺。 @Bergi 我需要在“then”下写什么才能返回正确的承诺?
  • 您只需省略then,并在您的表达式前面加上return。请向我们展示您的尝试。
  • @Bergi 我在这个问题中添加了我的尝试。如何正确返回表达式?
  • 删除除return requestPoll({…}); 之外的所有行,并删除callback 参数。如果您需要解析结果,请将.then(JSON.parse) 添加到其中。然后将所有调用更改为使用 promise 而不是传递回调。

标签: javascript callback promise mocha.js sinon


【解决方案1】:

我建议您不要混合使用承诺和回调。如果你已经有了基于 Promise 的函数,请坚持使用它

首先让getMessages 不破坏承诺链。让它返回一个 Promise

getMessages: function(counter) {
  return requestPoll({
    method: "GET",
    action: "http://localhost:9090/messages?counter=" + counter
  }).then(JSON.parse)
}

然后在你的测试中使用这个承诺

it('should issue GET /messages ', function() {
  server.respondWith('GET', `${apiUrl}/messages?counter=0`, JSON.stringify([{testdata}]));
  const gettingMessages = Babble.getMessages(0);
  server.respond();

  // return a promise so testing framework knows the test is async
  return gettingMessages.then(function(messages) {
      // make assertion messages is actually testdata
  })
})

【讨论】:

    猜你喜欢
    • 2015-07-15
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 2018-01-13
    • 2020-05-12
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多