如何在Angular单元测试中模拟/侦察导入的函数

use*_*820 11 unit-testing mocking spy angular

假设我有一个角度为6的组件,其方法test返回一些值:

import { doSomething } from './helper';

@Component({
    ...
})
export class AppComponent {
    test() {
        const data = doSomething(1);
        return data.something ? 1: 2;
    }
}
Run Code Online (Sandbox Code Playgroud)

doSomething 只是一个简单的辅助函数:

export function doSomething() {
    return { something: 1 };
}
Run Code Online (Sandbox Code Playgroud)

是否可以在单元测试中模拟或监视此函数(因此我可以控制其returnValue)?或者我是否必须更改组件中的方法?

请注意:doSomething()可以是lodash函数,const,类等.我只是尽量保持示例尽可能简单.


我试过的事情:

  • SpyOn 不起作用,因为函数没有附加到任何东西

  • 将mock函数导入给出的imports数组中TestBed.configureTestingModuleUnexpected value 'doSomething' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.

  • 为它创建服务有效,但必须为每个导入的函数创建服务感到愚蠢

小智 12

在您的spec文件中以这种方式导入帮助程序:

import * as helper from './helper';
Run Code Online (Sandbox Code Playgroud)

在你的it()中你可以监视辅助对象并返回请求的值:

spyOn(helper, 'doSomething').and.returnValue({});
Run Code Online (Sandbox Code Playgroud)

  • 尝试此操作时,我收到以下错误:错误:<spyOn>:doSomething 未声明为可写或没有 setter Angular 7 (CLI) (11认同)
  • @PeterI 我在另一个线程中发布了一个解决方案:/sf/answers/3833009841/ (3认同)
  • 相同.@rryter你找到了解决方案吗? (2认同)