javascript - 无法让 chai.spy.on 工作

标签 javascript unit-testing chai

请不要建议使用 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();
});

如果这不起作用,那么它更具体到您对 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;
    });
});

关于javascript - 无法让 chai.spy.on 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33849605/

相关文章:

javascript - 如何改变GridHelper线条的粗细?

javascript - 为 React-Native 应用开 Jest 测试 Animated.View

javascript - Mocha 测试超时

javascript - 如何使用 cron 从 bash 运行 Node 脚本

javascript - Vue js 带条件的 for 循环

javascript - 类型错误:f 不是函数

unit-testing - 我如何知道何时使用基于状态的测试和模拟测试?

c# - 断言后如何获取异常对象?

javascript - 如何使用 sinon.js 模拟/监视 javascript 函数中提到的对象?

node.js - 如何从单个文件夹运行 npm 测试?