ps0604
ps0604

Reputation: 1071

Mocking Angular service in Jasmine throws method not found

In this plunk I have an Angular/Jasmine test that attempts to mock a service function. The service function mocked needs to be invoked by another function in the service.

This is the error I get:

Error: getTheDate() method does not exist

And this is my attempt, where the function tested getTheMonth should invoke a mocked function getTheDate, it seems that spyOn is used incorrectly:

angular.module("mymodule", [])

.service('myService', function(){

    this.getTheDate = function() {
        return new Date();
    };


    this.getTheMonth = function() {
         var d = this.getTheDate();
         return d.getMonth();
    };
})

describe("Testing date functions", function() {

    beforeEach(function(myService) {
        module("mymodule");
        var d = new Date();
        d.setDate(12)
        d.setMonth(2);
        d.setFullYear(2018);
        spyOn(myService, 'getTheDate').and.returnValue(d);
    });


    it('should return the month',

        inject(function(myService) {

        expect(myService.getTheMonth()).toEqual(2);


    }));

});

Upvotes: 0

Views: 433

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

beforeEach(function(myService) {
  module("mymodule");

should be

beforeEach(module("mymodule"));
beforeEach(inject(function(myService) {

Updated plunkr

Upvotes: 1

Related Questions