2

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?

7
  • 2
    Maybe pass a spy (jasmine.createSpy()) as the error callback and check with expect(mySpy).not.toHaveBeenCalled();? Commented Jun 28, 2014 at 21:25
  • Have a look on the Spies Commented Jun 28, 2014 at 21:26
  • Related to the spy suggestions have a look at the async testing support in 2.0 and in 1.3 too. Commented Jun 28, 2014 at 21:44
  • auth.login should return promise that you must reject. Commented Jun 28, 2014 at 22:12
  • @KrzysztofSafjanowski: What do you mean? Commented Jun 28, 2014 at 23:08

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

@cdmckay - please explain me - how you want to test mySpy callback that should be faired on error?
1
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.