【发布时间】:2014-04-18 23:41:58
【问题描述】:
我有一个规范来测试是否调用了范围内的方法(见下文)
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
});
【问题讨论】:
-
这里的问题可能对其他人来说是显而易见的,但您是否意识到您可以在浏览器(如 Chrome 或 Firefox)中执行单元测试,并单步执行您的代码以查看它在做什么?您可以在命令行上执行 Karma 并使用浏览器中的调试器来执行此操作。
-
@DavidM.Karr 您的建议以某种方式引导我找到答案。
Spyon正在改变我的trigger函数,所以它确实没有达到我想要的效果。所以删除了那段代码