TJ TJ
TJ TJ

Reputation: 37

Jasmine, AngularJS: Unit test a function which returns a value after timeout

I'm not sure where I'm going wrong with this test.

Service Code:

self.clearMessage = function(interval) {
  if (!interval)
    interval = 2000;

  return $timeout(function() {
    return '';
  }, interval);
};

Spec:

it('clears message', function() {
  var result = self.clearMessage();

  $timeout.flush();

  expect(result).toBe('');
});

I've also tried triggering a digest cycle in test with no success. I'be never run into this issue before, as I generally would be setting an external variable inside the timeout block - that works fine for unit testing.

In this scenario, when there is only a return inside the timeout I receive the following error:

Expected Promise({ $$state: Object({ status: 1, value: '' }), $$timeoutId: 1 }) to be ''.

EDIT / ANSWER

it('clears message', function() {
  self.clearMessage().then(function(response) {
    expect(response).toBe('');
  })

  $timeout.flush();
});

Upvotes: 1

Views: 846

Answers (1)

MS_AU
MS_AU

Reputation: 412

Calling AngularJS's $timeout service from within your Service Code is returning you a Promise. This Promise will... "be resolved when the timeout is reached. The promise will be resolved with the return value of the fn function." https://docs.angularjs.org/api/ng/service/$timeout

You'll need something like this in your Spec:

var result = self.clearMessage();
result.then(function(value) {
  expect(value).toBe('');
});

$timeout.flush();  

JSFiddle

Upvotes: 1

Related Questions