请不要建议使用 Sinon。我想让 chai-spies 特别是 chai.spy.on 在你的帮助下工作。基本上,我有这个规范。在 PatientController 的初始化方法中,我调用了 this.initializePatientEvents();
beforeEach(function() {
this.patientController = new PatientController({model: new Backbone.Model(PatientModel)});
});
it('executes this.initializePatientEvents', function () {
let spy = chai.spy.on(this.patientController, 'initializePatientEvents');
expect(spy).to.have.been.called();
});
但是,测试失败并出现此错误
AssertionError: expected { Spy } to have been called
at Context.<anonymous>
我现在花了将近 3 个小时,但没有运气! :(
最佳答案
将我上面的评论移至此处的回复:
查看您的代码,我只是不确定 this
引用指的是什么。根据您的错误消息,它似乎与上下文有关。因此,我会尝试这样的事情:
var patientController;
beforeEach(function() {
patientController = new PatientController({model: new Backbone.Model(PatientModel)});
});
it('executes this.initializePatientEvents', function () {
let spy = chai.spy.on(patientController, 'initializePatientEvents');
expect(spy).to.have.been.called();
});
如果这不起作用,那么它更具体到您对 patientController
和 initializePatientEvents
方法的实现,而不是与 chai.spy 相关的东西。
编辑: 这是我在本地设置的东西,我能够通过测试。主要区别在于我没有使用 Backbone,而是创建了自己的构造函数。
"use strict";
var chai = require("chai");
var sinon = require("sinon");
var sinonChai = require("sinon-chai");
chai.use(sinonChai);
var expect = chai.expect;
var should = chai.should();
describe("PatientController Test", function() {
var PatientController;
var initializePatientEventsSpy;
var patient;
beforeEach(function() {
PatientController = function(name, age) {
this.name = name;
this.age = age;
this.initializePatientEvents();
};
PatientController.prototype.initializePatientEvents = function() {
console.log("Do some initialization stuff here");
};
initializePatientEventsSpy = sinon.spy(PatientController.prototype, "initializePatientEvents");
});
it("should test initializePatientEvents was called", function() {
patient = new PatientController("Willson", 30);
initializePatientEventsSpy.should.have.been.called;
});
});
关于javascript - 无法让 chai.spy.on 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33849605/