我有一个规范,测试范围内的方法是否被调用(见下文)
describe("Event Module tests", function () {
var scope, simpleController;
beforeEach(module('SimpleApplication'));
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
simpleController = $controller("SimpleController", {
$scope: scope
});
}));
it("Scope function should be triggered", function () {
spyOn(scope, "trigger");
scope.trigger();//invoke the function on controller
expect(scope.trigger).toHaveBeenCalled();//Passes
expect(scope.isTriggered).toBeTruthy();//Fails
});
});
申请代码(待测代码):
angular
.module("SimpleApplication", [])
.controller("SimpleController", function ($scope) {
$scope.message = "Hello World";
$scope.isTriggered = false;
$scope.trigger = function() {
$scope.isTriggered = true;
};
});
Jasmine报道说“预期虚假是真的”。怎么会 ?因为该方法将其设置为true !!
更新
出于某种原因,SpyOn正在将我的对象变为它想要的东西。所以下面的代码很好用
it("Scope function should be triggered", function () {
scope.trigger();//invoke the function on controller
expect(scope.isTriggered).toBeTruthy();//Now Passes
});
答案 0 :(得分:2)
spyOn
不会调用您的方法。它只是间谍。如果你想要它被调用,你必须添加一些东西:
spyOn(scope, "trigger").andCallThrough()