0

Simply Put:

Can I match mock-$httpBackend data from $resource service in a jasmine unit test? How would I do it?

What I Want:

When I Jasmine-test my backend services with $httpBackend and the $http service, I can do this:

  it("should return movie search data from the title", function() {
    var movieData = { title: "The Phantom Menace", description: "A movie.";
    var response = [];

    $httpBackend.when('GET', 'http://www.omdbapi.com/?v=1&s=the%20phantom%20menace')
      .respond(200, movieData);

    moviesService.search('the phantom menace')
      .then(function onSuccess(data) {
        response = data;
      });

    $httpBackend.flush();

    expect(response.data).toEqual(movieData);
  }); // end it

I have all of The Phantom Menace's information stored in movieData. This test passes because it compares the data that is received from the mock backend to what it should be (movieData).

What I Am Getting:

When I Jasmine-test my backend services with $httpBackend and the $resource service, things are different.

 it("retrieves a bunch objects", function() {
    var result = {}, testArray = [];
    var dataToCheck = [
      { id: 1, "des": "This is one."},
      { id: 2, "des": "This is two."},
      { id: 3, "des": "This is three."}
    ];

    $httpBackend.whenGET('movies/api')
      .respond(dataToCheck);

    MovieResource.query().$promise.then(function (data) {
      result = data;
    });

    $httpBackend.flush();

    angular.forEach(result, function (resource) {
      testArray.push(resource);
    })

    expect(testArray).toEqual(dataToCheck);
  }); // end it

Karma tells me:

Expected [ Resource({ id: 1, des: 'This is one.' }), Resource({ id: 2, des: 'This is two.' }), Resource({ id: 3, des: 'This is three.' }) ] to equal [ Object({ id: 1, des: 'This is one.' }), Object({ id: 2, des: 'This is two.' }), Object({ id: 3, des: 'This is three.' }) ].

So, instead of "Objects" they are "Resources."

I appreciate ANY guidance you can give me.

Gabriel Kunkel
  • 2,643
  • 5
  • 25
  • 47

1 Answers1

0

You will need to do something like this

expect(testArray[0].id).toEqual(dataToCheck[0].id);
expect(testArray[1].id).toEqual(dataToCheck[1].id);
expect(testArray[0].des).toEqual(datatoCheck[0].des);

Reference: http://accraze.info/testing-angular-services-using-jasmine/

muhammadn
  • 330
  • 3
  • 18