如何测试未调用函数?


84

我正在测试路由器,并且具有两个功能,并且我需要测试是否调用了第一个功能,是否未调用第二个功能。有方法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?
});

Answers:


159

使用not运算符:

expect(controller.bar).not.toHaveBeenCalled();
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.