【问题标题】:Jasmine test for scope methods fails范围方法的 Jasmine 测试失败
【发布时间】: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 函数,所以它确实没有达到我想要的效果。所以删除了那段代码

标签: angularjs jasmine bdd spy


【解决方案1】:

spyOn 不会调用你的方法。它只是间谍。如果你想调用它,你必须添加一些东西:

spyOn(scope, "trigger").andCallThrough()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-10
    • 2020-03-13
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    相关资源
    最近更新 更多