Testing controller with injected service inside angularJS with jasmine

前端 未结 1 694
星月不相逢
星月不相逢 2021-02-15 15:00

I am trying to understand how to test my code with jasmine and angularJS. I wrote a test project with a controller and an injected service. Now i want to test the controller and

1条回答
  •  孤城傲影
    2021-02-15 15:40

    You should use $provide.value in order to replace the original service instance with a mocked one:

    beforeEach(module(function($provide) {
        var service = { 
            Arrive: function (firstname, lastname) {
                if (firstname && lastname) {
                    return true;
                }
            }
        };
        $provide.value('MyService', service);
    }));
    

    I really don't know why $provide.value works but $provide.factory doesn't. I'll try to take a look at the Angular code later so I can figure it out. I'll update this answer if I find out something.

    About spies, you should use them if you want to test that your mocks are being used the way they are supposed to. That includes checking parameters and invocations. Here's your code changed to use a spy:

    it('checks that Arrived is correctly used', function() {
        // Arrange
        spyOn(service, 'Arrive');
    
        // Act
        scope.Arrived('Franz', 'Kafka');
    
        // Assert
        expect(service.Arrive).toHaveBeenCalledWith('Franz', 'Kafka');
    });
    

    Here's your fixed jsFiddle.

    0 讨论(0)
提交回复
热议问题