无法让 chai.spy.on 工作

Can't get chai.spy.on to work

请不要建议使用诗乃。我特别想让 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();
});

如果这不起作用,那么它更具体地针对您对 patientControllerinitializePatientEvents 方法的实施,而不是与 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;
    });
});

如果 PatientController 构造函数调用 initializePatientEvents,那么您创建间谍的时机有点不对。目前,您的 spy-function 关系的顺序是:

  1. 调用函数
  2. 监视功能
  3. 预期函数被 ben 调用

因为函数在调用时没有被监视,所以间谍完全错过了调用。顺序应该是:

  1. 监视功能
  2. 调用函数
  3. 预期函数被 ben 调用

但是,您处于一种棘手的情况,您正在监视的对象在调用构造函数之前不存在。一种解决方法是断言 initializePatientEvents 的效果已经发生,而不是断言函数已被调用。