【问题标题】:Sinon.spy fails with imported methodSinon.spy 使用导入的方法失败
【发布时间】:2018-08-02 05:00:06
【问题描述】:

我有几个 JS 模块,比如说 A 和 B。在模块 A 中,我有一个方法依赖于从模块 B 导入的另一个方法。现在我如何用 sinon.spy 测试,是否来自 A 的方法触发B的方法?

//ModuleA.js
import{ methodFromB } from "ModuleB.js";

function methodFromA (){
methodFromB();
}

export{
 methodFromA
}

//ModuleB.js
function methodFromB (){ 
 //doSomething
}

ModuleA.Spec.js

import sinon from 'sinon';
import { assert,expect } from "chai";
import * as modB from "ModuleB.js";

import { methodA } from '../js/ModuleA.js';


describe("ModuleA.js", function() {

beforeEach(function() {
    stubmethod = sinon.stub(modB, "methodB").returns("success");              
});

after(function() {

});

describe("#methodA", function() {
    it("Should call the method methodB", function() {
        expect(methodA()).to.deep.equal('success');
        expect(stubmethod.calledOnce).to.equal(true);
    });

});    

});

在尝试存根 methodB 后,我收到错误“预期未定义到完全等于‘成功’”。

提前致谢。

【问题讨论】:

    标签: javascript unit-testing sinon sinon-chai


    【解决方案1】:

    你应该模拟模块 B,并期望它 to.have.been.call 而不是来自 methodFromA 的 spy

    【讨论】:

    • 我尝试了subbing methodB,但我遇到了错误“预计未定义到完全等于'成功'”。
    【解决方案2】:

    您从 module B 存根错误的函数。根据您的源文件,它应该是 methodFromB 而不是 methodB

    describe("ModuleA.js", function () {
    
      beforeEach(function () {
        stubmethod = sinon.stub(modB, "methodFromB").returns("success"); // change to methodFromB
      });
    
      after(function () {
        stubmethod.restore(); // don't forget to restore
      });
    
      describe("#methodA", function () {
        it("Should call the method methodB", function () {
          expect(methodA()).to.deep.equal('success');
          expect(stubmethod.calledOnce).to.equal(true);
        });
    
      });
    });
    

    【讨论】:

    • 谢谢。我想我找到了根本原因。
    • @MuraliNepalli 是什么原因?
    • @deerwan 我更正了您指出的错字,但实际原因是模块 B 中的“methodFromB”没有返回值。因此我不能用返回值“成功”来替换它。如果方法有返回值让我们说“返回”“某事”,那么我的存根就可以工作了。
    • @MuraliNepalli 很高兴找到真正的问题?
    猜你喜欢
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 2019-08-15
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    相关资源
    最近更新 更多