mercredi 6 juillet 2016

What type of spy to use for testing

I know when you use spyOn you can have different forms like .and.callFake or .andCallThrough. I'm not really sure which one I need for this code I'm trying to test...

  var lastPage = $cookies.get("ptLastPage");
      if (typeof lastPage !== "undefined") {
        $location.path(lastPage);
      } else {
        $location.path('/home'); //TRYING TO TEST THIS ELSE STATEMENT
      }
    }

Here is some of my test code:

describe('Spies on cookie.get', function() {
    beforeEach(inject(function() {
      spyOn(cookies, 'get').and.callFake(function() {
        return undefined;
      });
    }));
    it("should work plz", function() {
      cookies.get();
      expect(location.path()).toBe('/home');
      expect(cookies.get).toHaveBeenCalled();
      expect(cookies.get).toHaveBeenCalledWith();
    });
  });

I've tried a lot of different things, but I'm trying to test the else statement. Therefore I need to make cookies.get == undefined. Everytime I try to do that though, I get this error:

Expected '' to be '/home'.

The value of location.path() never changes when cookies.get() is equal to undefined. I think I'm using the spyOn incorrectly?

Follow-up on my mock values:

beforeEach(inject(
    function(_$location_, _$route_, _$rootScope_, _$cookies_) {
      location = _$location_;
      route = _$route_;
      rootScope = _$rootScope_;
      cookies = _$cookies_;
    }));

Aucun commentaire:

Enregistrer un commentaire