Javascript 调用同一文件中的测试函数

Javascript 调用同一文件中的测试函数,javascript,angular,typescript,testing,karma-runner,Javascript,Angular,Typescript,Testing,Karma Runner,我有两个函数,一个调用另一个,另一个返回一些东西,但我无法让测试正常工作 使用expect(x).调用(someParams)希望使用间谍,但我不知道如何在同一文件中间谍函数 错误::应为间谍,但获得了函数 用法:expect().toHaveBeenCalledWith(…参数) 示例.ts doSomething(word: string) { if (word === 'hello') { return this.somethingElse(1); } ret

我有两个函数,一个调用另一个,另一个返回一些东西,但我无法让测试正常工作

使用
expect(x).调用(someParams)
希望使用间谍,但我不知道如何在同一文件中间谍函数

错误::应为间谍,但获得了函数

用法:expect().toHaveBeenCalledWith(…参数)

示例.ts

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

somethingElse(num: number) {
   var x = { "num": num };
   return x;
}
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);
});
示例.spec.ts

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

somethingElse(num: number) {
   var x = { "num": num };
   return x;
}
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);
});

在您的Example.spec.ts中,只需添加一个
spyOn(组件'somethingElse')作为
测试的第一行('应该调用somethingElse…
测试:

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

expect方法在
之前使用时需要一个Spy作为参数,以便与
一起调用(
)。

谢谢你的提示!我试图通过将
mySpy=spyOn(component,'somethingElse');
放在
beforeach()
部分来让它工作,但它不会花费太多时间。