2017-05-02 52 views
0

所以基本上我有我想要测试,我们将调用函数A.我想测试,如果函数B被调用函数的内部函数。问题在于函数B在函数A中被解析的Promise异步调用。这将导致sinon断言失败,因为测试将在函数B被调用之前完成!如何测试,如果函数A被调用的测试函数B内,如果它被称为异步

这是一个工作代码场景。

const sinon = require('sinon'); 

describe('functionToBeTested',() => { 
    it('someFunction is called',() => { 
    // spy on the function we need to check if called 
    const spy = sinon.spy(someClass.prototype, 'someFunction'); 
    // call the function being tested 
    functionToBeTested(); 
    // check if spy was called 
    sinon.assert.called(spy); 
    }); 
}); 

class someClass { 
    someFunction() { 
    console.log('Hello'); 
    } 
} 

const somePromise = Promise.resolve(); 

function functionToBeTested() { 
    const instance = new someClass(); 
    // some synchronous code here 
    // if instance.someFunction() is called here the test will pass 
    // . 
    // . 
    // . 
    somePromise.then(() => { 
    instance.someFunction(); 
    // the function is called and Hello is printed but the test will fail 
    }) 
    // . 
    // . 
    // . 
    // some synchronous code here 
    // if instance.someFunction() is called here the test will pass 
} 

回答

1

你的例子有点不合常规。您有functionToBeTested它具有双重行为(同时同步和异步)。当您将此方法置于测试中时,应该事先了解并标准化该行为,以便相应地构建测试和断言。

在这种情况下的问题是,你试图验证功能的行为是同步模式,虽然内部零件工作在一个随时忘记时尚 - 即没有依赖的结果instance.someFunction()方法。

如果functionToBeTested()返回一个承诺 - 因此是异步的设计,这将是你的测试场景的直接。但在这种情况下,您还需要一种非传统的测试方法。这意味着如果你做类似的事情:

describe('functionToBeTested',() => { 

    it('someFunction is called', (done) => { 

     // spy on the function we need to check if called 
     const spy = sinon.spy(SomeClass.prototype, 'someFunction'); 

     // call the function being tested 
     functionToBeTested(); 

     setTimeout(() => { 
      // check if spy was called 
      sinon.assert.called(spy); 
      done(); 
     }, 10); 

    }); 
});  

测试会通过。这里发生的是我们通过在回调中使用完成的参数来声明测试async。此外,我们添加了一个计时器来模拟延迟,然后检查是否调用了间谍。

由于''忘记''电话只打印出一条信息,等待10ms就足够了。如果承诺花费较长时间完成,则应等待时间调整。如前所述,非常规实现需要非常规方法。我建议您重新考虑您的要求并重新设计解决方案。

相关问题