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

2022-08-30 04:46:55

我正在测试路由器,并且有两个函数,我需要测试是否调用了第一个函数,第二个函数没有被调用。有方法,但没有方法来测试是否未调用函数。我该如何测试?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?
});

答案 1

使用运算符:not

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

答案 2