【问题标题】:Testing function within same file is called调用同一文件中的测试函数
【发布时间】:2018-08-29 08:58:00
【问题描述】:

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

使用expect(x).toHaveBeenCalledWith(someParams); 需要使用间谍,但我不知道如何在同一文件中窥探函数...

错误: : 预期是间谍,但得到了函数。

用法: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);
});

【问题讨论】:

    标签: javascript angular typescript testing karma-runner


    【解决方案1】:

    在您的 Example.spec.ts 中,只需添加一个 spyOn(component, 'somethingElse'); 作为您的 it('should call 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 方法在 toHaveBeenCalledWith 之前使用时需要一个 Spy 作为参数(根据 Jasmine documentation)。

    【讨论】:

    • 感谢您的提示!我试图通过将mySpy = spyOn(component, 'somethingElse'); 放入beforeEach() 部分来使其工作,但它不会。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 2018-05-06
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多