简体   繁体   English

Sinonjs消耗诺言的测试方法

[英]Sinonjs test method that consumes a promise

I have a javascript method that looks something like this: 我有一个javascript方法,看起来像这样:

someMethod=function(){
  somePromise.run().then(()=>{
    //do success stuff
  }).catch((err)=>{
    //do fail stuff
    registerError(err);
  });
}

I want to make sure that the error is getting registered, so I've set up the following test. 我要确保错误已得到注册,因此我设置了以下测试。

it('should register error', ()=>{
  somePromise = {
    run: sinon.stub
  };
  registerError = sinon.stub;
  somePromise.returns(Promise.reject({err: 'foo'}));
  someMethod();
  assert(registerError.calledWith({err: 'foo'}));
});

This test fails because the assert fires before the promises in someMethod finish. 该测试失败,因为断言在someMethod中的诺言完成之前触发。 I could update someMethod to return a promise, but that smells fishy to me. 我可以更新someMethod来返回一个诺言,但这对我来说有点腥。 Any input is welcome, thanks! 欢迎任何输入,谢谢!

You have created an async method that does not return either a promise or contain a callback as an argument. 您创建了一个异步方法,该方法既不返回promise也不包含回调作为参数。 This is not a good practice as you cannot know when your async function will finish. 这不是一个好习惯,因为您不知道异步功能何时完成。 A simple fix is to return the promise from the function and perform your assert as a part of the promise chain. 一个简单的解决方法是从函数中返回承诺,并将您的断言作为承诺链的一部分执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM