cdmckay
cdmckay

Reputation: 32240

How to make a Jasmine test fail when code is run

I'm testing an AngularJS service, and as part of it, I want to make sure a certain callback is never called. Right now, my test looks like

it('should succeed to login the user', function () {
  var params = {
      email: '[email protected]',
      password: 'hunter2'
  };
  var member = {
      remoteAddress: '1.2.3.4'
  };
  $httpBackend.expectPOST(fakeApiUrl + '/1/authentication/login', params)
      .respond(200, member);
  auth.login(params.email, params.password).then(
      function (m) {
          expect(m.remoteAddress).toBe(member.remoteAddress);
      },
      function () {
          // I want this to be fail()
          expect(true).toBe(false);
      }
  );
  $rootScope.$digest();
  $httpBackend.flush();
});

The problem is, in order to make the test fail if that callback is triggered, I have to do something dirty like expect(true).toBe(false).

Is there a better way to accomplish this? For example, is there a more appropriate matcher I could be using, or should I be structuring my test differently?

Upvotes: 2

Views: 172

Answers (2)

Anthony Chu
Anthony Chu

Reputation: 37520

One way to do it is to create a spy and assert that the spy was never called...

var mySpy = jasmine.createSpy('mySpy');

$httpBackend.expectPOST(fakeApiUrl + '/1/authentication/login', params)
  .respond(200, member);
auth.login(params.email, params.password).then(
  function (m) {
      expect(m.remoteAddress).toBe(member.remoteAddress);
  },
  mySpy
);
$rootScope.$digest();
$httpBackend.flush();

expect(mySpy).not.toHaveBeenCalled();

Upvotes: 1

Krzysztof Safjanowski
Krzysztof Safjanowski

Reputation: 7438

it('should succeed to login the user', function () {
    var params = {
        email: '[email protected]',
        password: 'hunter2'
    };

    auth.login = jasmine.createSpy().andReturn($q.reject());

    auth.login(params.email, params.password).then(

    function (m) {
        expect(m.remoteAddress).toBe(member.remoteAddress);
    },

    function () {
        // I want this to be fail()
        expect(true).toBe(false);
    });

    $scope.$digest();
});

http://jsfiddle.net/zk8Lg/1/

Upvotes: 1

Related Questions