physicsboy
physicsboy

Reputation: 6348

Cannot get spyOn test to work properly- Angular

I cannot get my test to work for some reason and it keeps throwing the error:

Expected spy on isCurrentStatus to equal true.

The function being called simply assessed whether the passed in variable equals the currently held status property, and returns either true of false. Nothing major...

Test

it('should return true if current status = status passed in', () => {
    const statusSpy = spyOn(component, 'isCurrentStatus');
    component.event = failedEvent;
    component.isCurrentStatus('failed');
    expect(statusSpy).toEqual(true);
  })

component

event: MyEvent;

isCurrentStatus(status: string): boolean {
    return this.event.status === status;
  }

UPDATE

I just moved the spyOn into the beforeEach() section and now returns:

expected undefined to equal true

Upvotes: 1

Views: 2416

Answers (3)

dsych
dsych

Reputation: 762

Expected spy on isCurrentStatus to equal true. It because spyOn creates, actually, a spy. And you try smth like expect(Spy).toEqual(Boolean); so you get such error.

expected undefined to equal true - you get because beforeEach()'s scope is not in your test function (it()) scope

As you want to test returned value - you don't need to spy here. Just call function and check its result.

Spy is needed when you need test not return value but something else - for example, it is function of injected dependency but you need to be confident that it was called. So, you create a spy. Or: you need to check how many times was function called, what params were passed etc. Or when you need to mock its behavior.

Upvotes: 1

lietutis
lietutis

Reputation: 201

you could create a spyOn on the function and check value it returns differently:

spyOn(component, 'isCurrentStatus').and.callThrough();
component.event = failedEvent;
const statusResult = component.isCurrentStatus('failed');
expect(statusResult).toBeTruthy();

Upvotes: 2

Fateh Mohamed
Fateh Mohamed

Reputation: 21367

try this to test the returned value

expect(component.isCurrentStatus('failed')).toEqual(true);

and you can check if the method was called or not

const statusSpy = spyOn(component, 'isCurrentStatus').and.callThrough();
...
expect(statusSpy).toHaveBeenCalledTimes(1);

you can check arguments

expect(statusSpy).toHaveBeenCalledWith('failed')

Upvotes: 0

Related Questions