unit-testing - Mocha sinon.spy 总是显示函数调用 0 次

标签 unit-testing mocha.js sinon chai spy

我是 Mocha/Chai 的新手。我正在尝试为以下场景编写单元测试用例。我想测试在调用“parent()”函数时是否调用“callchildfunc”和“childfunc2”。

我已经阅读了基础知识,我的理解是,如果您正在监视任何函数,那么只需在该函数上放置断言即可检查该函数是否被调用。在上面的脚本文件中意味着如果我将监视“childfunc2”和“callchildfunc”函数,那么我不需要在测试文件中调用这里,因为它已经在父函数下的脚本文件中调用。如果我的理解有误,请指正。

这是我的 script.js 文件

// script.js    

function childfunc2(){
    console.log("child function without return");
}
function callchildfunc(var1, var2){
   return var1 + var2;
}
function parent(x){
   var getreturnval = callchildfunc(x, 1);
   console.log(getreturnval);
   childfunc2();
}

这是我的测试文件。

//scenario 1

describe('Test for parent() function ', function(){
   it('should make parent call ', function(){

        var spy1 = sinon.spy(window, 'callchildfunc');
        var spy2 = sinon.spy(window, 'childfunc2');
        parent(2);
        expect(spy1).to.have.been.called();
        expect(spy2).to.have.been.called();
        // or
        sinon.assert.calledOnce(spy1);
        sinon.assert.calledOnce(spy1);

    });
});

运行测试后我总是收到此错误。

AssertError: expected childfunc2 to be called once but was called 0 times

此外,如果我更改测试文件并调用 spy 函数,那么它就会起作用。

var spy1 = sinon.spy(window, 'callchildfunc');
var spy2 = sinon.spy(window, 'childfunc2');
parent(2);
// After addding these below 2 lines.
window.childfunc2();
window.callchildfunc();

有什么帮助吗?

最佳答案

// Script.js 

module.exports= {
childfunc2:function(){
    console.log("child function without return");
},
callchildfunc:function(var1, var2){
   return var1 + var2;
},
parent:function(x){
   var getreturnval = this.callchildfunc(x, 1);
   console.log(getreturnval);
   this.childfunc2();
}
};

//测试.js

var sinon= require('sinon'), expect=require('chai').expect
var r= require('./functests')
describe('Test for parent() function ', function(){
   it('should make parent call ', function(){
        var spy1 = sinon.spy(r, 'callchildfunc');
        var spy2 = sinon.spy(r, 'childfunc2');
        r.parent(2);
//        expect(spy1).to.have.been.called();
  //      expect(spy2).to.have.been.called();
        // or
        sinon.assert.calledOnce(spy1);
        sinon.assert.calledOnce(spy1);

    });
});

//截图

enter image description here

关于unit-testing - Mocha sinon.spy 总是显示函数调用 0 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49401214/

相关文章:

unit-testing - 自动化测试 : Tool for Visualizing and archiving test results

php - PHPUnit 测试的目录布局?

django - 如何使用外键在 Django 中测试模型

node.js - 使用 Mocha 运行类似的测试

java - 如何让 MockFTPServer 抛出异常

javascript - Mocha 在测试中提供 "not a function response"

node.js - 如何为 Mocha 定义测试目录?

node.js - Stubbing Fetch Call - response.json 不会调用

javascript - 没有调用Sinon Spy,但调用了原始函数

javascript - 与 Chai 和 Sinon 一起测试 promise 的服务