Paul H
Paul H

Reputation: 670

toHaveBeenCalled() returns undefined

As far as I understand, the .toHaveBeenCalled() Matcher of jasmine returns a Promise which is resolved when the function has been called. Actually for me, it returns undefined:

it('should show the first entries', () => {
  expect(contentfulService.first)
    .toHaveBeenCalled()
    .then(() => {
      expect(component.entries).toBe(entriesMock);
    });
});

The first method of the contentfulService is spied on like this:

contentfulService = TestBed.get(ContentfulService);
spyOn(contentfulService, 'first').and.callThrough();

The spec fails telling me:

TypeError: Cannot read property 'then' of undefined

I double checked it. It's definitely the result of toHaveBeenCalled() that returns undefined. Why? Am I getting something wrong?

Upvotes: 0

Views: 1077

Answers (1)

Pace
Pace

Reputation: 43817

toHaveBeenCalled is an assertion method (like toBe or toEqual). It is a synchronous method that fails the test if the mock has not been called and it returns undefined.

Usually you call it at the end of the test to verify your code did what it was supposed to. It is not meant to be used for flow control.

Upvotes: 3

Related Questions