1

I have 2 functions where one calls the other and the other returns something, but I cannot get the test to work.

Using expect(x).toHaveBeenCalledWith(someParams); expects a spy to be used, but I am unaware of how to spy on a function within the same file...

Error: : Expected a spy, but got Function.

Usage: expect().toHaveBeenCalledWith(...arguments)

Example.ts

doSomething(word: string) {
   if (word === 'hello') {
      return this.somethingElse(1);
   }
   return;
}

somethingElse(num: number) {
   var x = { "num": num };
   return x;
}

Example.spec.ts

fake = {"num": "1"};

it('should call somethingElse', () => {
    component.doSomething('hello');
    expect(component.somethingElse).toHaveBeenCalledWith(1);
});

it('should return object', () => {
    expect(component.somethingElse(1)).toEqual(fake);
});
Community
  • 1
  • 1
physicsboy
  • 5,656
  • 17
  • 70
  • 119

1 Answers1

1

In your Example.spec.ts, just add a spyOn(component, 'somethingElse'); as first line of your it('should call somethingElse ... test :

fake = {"num": "1"};

it('should call somethingElse', () => {
    // Add the line below.
    spyOn(component, 'somethingElse');
    component.doSomething('hello');
    expect(component.somethingElse).toHaveBeenCalledWith(1);
});

it('should return object', () => {
    expect(component.somethingElse(1)).toEqual(fake);
});

The expect method needs a Spy as parameter when used before a toHaveBeenCalledWith (as per the Jasmine documentation).

faflo10
  • 386
  • 5
  • 13
  • Thanks for the hint! I was trying to get it working by putting `mySpy = spyOn(component, 'somethingElse');` in the `beforeEach()` section, but it wouldn't take. – physicsboy Aug 29 '18 at 12:50