如何测试函数是否未被调用?

问题描述 投票:0回答:1

我正在测试路由器并有两个功能,我需要测试第一个功能是否被调用而第二个功能是否没有。有方法

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个回答
256
投票

使用

not
运算符:

expect(controller.bar).not.toHaveBeenCalled();
© www.soinside.com 2019 - 2024. All rights reserved.