javascript - 如果异步调用,如何在测试函数B内部测试函数A是否被调用

标签 javascript unit-testing mocha.js sinon sinon-chai

所以基本上我有我想测试的函数,我们将调用函数 A。我想测试函数 B 是否在函数 A 内部被调用。问题是函数 B 是通过已解析的 Promise 在函数 A 中异步调用的.这将导致 sinon 断言失败,因为测试将在调用函数 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
} 

最佳答案

您的示例有点不合常规。您有 functionToBeTested,它具有双重行为(同时同步和异步)。当您测试此方法时,行为应该是众所周知的并事先标准化,以便您可以相应地构建测试和断言。

此场景中的问题是您尝试验证函数的行为是同步模式,尽管内部部分以即发即弃方式工作 - 即不依赖于instance.someFunction() 方法的结果。

如果 functionToBeTested() 返回一个 promise - 因此在设计上是异步的,这对于您的测试场景来说将是直截了当的。但在这种情况下,您还需要一种非常规的测试方法。这意味着如果您执行以下操作:

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);

    });
});    

测试会通过。这里发生的事情是,我们通过在回调中使用 done 参数来声明测试 async。此外,我们添加了一个计时器来模拟在检查 spy 是否被调用之前的延迟。

由于“即发即弃”调用仅打印出一条消息,因此等待 10 毫秒就足够了。如果 promise 需要更长的时间才能完成,则应调整等待时间。

如前所述,非常规实现需要非常规方法。我建议您重新考虑您的要求并重新设计解决方案。

关于javascript - 如果异步调用,如何在测试函数B内部测试函数A是否被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43742358/

相关文章:

javascript - EasyQuery - 通过代码添加子查询

javascript - 无法转换为对象

javascript - 在 Mocha 测试中使用 for 循环

php - 如何将 DOM 树转换为图像

javascript - 如何使用 PHP 将局部变量调用到另一个函数中

java - 使用 Java 测试平面文件内容和格式

unit-testing - MVC3 中的单元测试 Controller session 变量

unit-testing - 黑盒单元测试

node.js - vuejs组件单元测试中定义的 'this'变量如何获取

testing - 如何使用 Jenkins 生成 mocha 测试用例报告并展示?