简体   繁体   English

范围方法的茉莉花测试失败

[英]Jasmine test for scope methods fails

I have an spec that test's if the method in scope was called (see below) 我有一个规范,用于测试范围中的方法是否被调用(请参见下文)

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

    });

});

Application Code(Code to be tested): 应用代码(待测试代码):

angular
    .module("SimpleApplication", [])
    .controller("SimpleController", function ($scope) {

        $scope.message = "Hello World";

        $scope.isTriggered = false;

        $scope.trigger = function() {
            $scope.isTriggered = true;
        };
    });

Jasmine reports that "Expected false to be truthy.". 茉莉花报道说“期望假是真”。 How come ? 怎么会 ? since the method sets it to true !! 因为该方法将其设置为true!

Update: 更新:

For some reason, SpyOn was mutating my object to something it was intended for. 由于某种原因,SpyOn会将我的对象更改为预期的对象。 So below piece of code works good 所以下面的代码效果很好

it("Scope function should be triggered", function () {

            scope.trigger();//invoke the function on controller

            expect(scope.isTriggered).toBeTruthy();//Now Passes

        });

spyOn doesn't call your method. spyOn不会调用您的方法。 It just spies. 它只是间谍。 If you want it to be called you have to add something: 如果要调用它,则必须添加一些内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM