首页 > 解决方案 > Sinon.spy 使用导入的方法失败

问题描述

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

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

function methodFromA (){
methodFromB();
}

export{
 methodFromA
}

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

模块A.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 后,我收到错误“预期未定义到完全等于‘成功’”。

提前致谢。

标签: javascriptunit-testingsinonsinon-chai

解决方案


您从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);
    });

  });
});

推荐阅读