Testing function within same file is called

我只是一个虾纸丫 提交于 2019-12-23 02:55:07

问题


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);
});

回答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).



来源:https://stackoverflow.com/questions/52073418/testing-function-within-same-file-is-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!