如何测试一个函数没有被调用?

2022-01-11 00:00:00 jasmine javascript

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

I'm testing router and have two functions, and I need to test if first function was called and second was not. There is method toHaveBeenCalled but there is no method to test if function was not called. How can I test that?

我有这样的代码:

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?
});

推荐答案

使用 not 运算符:

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

相关文章