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

标签 javascript angular typescript testing karma-runner

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

使用 expect(x).toHaveBeenCalledWith(someParams); 期望使用 spy ,但我不知道如何监视同一文件中的函数...

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

示例.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);
});

最佳答案

在您的 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);
});

当在 toHaveBeenCalledWith 之前使用时,expect 方法需要一个 Spy 作为参数(根据 Jasmine documentation )。

关于javascript - 调用同一文件中的测试函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52073418/

相关文章:

javascript - 掉落时不工作

javascript - Vue 有类似 Svelte 的命运操作符的东西吗?

javascript - Phonegap 插件 :retrive user profile, 电子邮件和 gmail

javascript - 无法在开发模式下运行 ng serve

node.js - Angular Jasmine 测试 HTML 注入(inject)失败

javascript - Gauge.js -> 需要将 javascript 修改为 PercentageColors 函数

angular - 需要在 Angular 应用程序内播放视频文件

javascript - 使用三元表达式在两个字符串值之间切换的正确方法

javascript - 对象 typescript/ionic 3 的接口(interface)

reactjs - TypeScript React 中可重用的布局组件 : Property 'path' does not exist on type 'IntrinsicAttributes & IProps'