【问题标题】:How can I test that a function has not been called?如何测试一个函数没有被调用?
【发布时间】:2014-08-08 13:29:57
【问题描述】:

我正在测试路由器并且有两个函数,我需要测试第一个函数是否被调用,第二个函数是否被调用。有方法toHaveBeenCalled,但是没有方法可以测试函数是否没有被调用。我该如何测试?

我有这样的代码:

var args, controller, router;
beforeEach(function() {
    controller = {
        foo: function(name, id) {
            args = [].slice.call(arguments);
        },
        bar: function(name) {
        }
    };
    spyOn(controller, "foo").and.callThrough();
    spyOn(controller, "bar").and.callThrough();
    router = new route();
    router.match('/foo/bar/{{id}}--{{name}}', controller.foo);
    router.match('/foo/baz/{{id}}--{{name}}', controller.bar);
    router.exec('/foo/bar/10--hello');
});
it('foo route shuld be called', function() {
    expect(controller.foo).toHaveBeenCalled();
});
it('bar route shoud not be called', function() {
    // how to test if bar was not called?
});

【问题讨论】:

    标签: javascript jasmine


    【解决方案1】:

    使用not 运算符:

    expect(controller.bar).not.toHaveBeenCalled();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-16
      • 2021-03-03
      • 2022-10-25
      • 2011-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多