小编use*_*820的帖子

如何在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.

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

unit-testing mocking spy angular

11
推荐指数
1
解决办法
6288
查看次数

标签 统计

angular ×1

mocking ×1

spy ×1

unit-testing ×1