繁体   English   中英

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

[英]How to mock/spy an imported function in Angular unit testing

假设我有一个带有方法test的 angular 6 组件,该组件返回一些值:

import { doSomething } from './helper';

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

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

export function doSomething() {
    return { something: 1 };
}

是否可以在单元测试中模拟或监视此函数(以便我可以控制其返回值)? 或者我必须改变我在组件中的方法吗?

请注意: doSomething()可以是一个 lodash 函数、一个常量、一个类等。我只是试图使示例尽可能简单。


我尝试过的事情:

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

  • 将模拟函数导入到TestBed.configureTestingModuleimports数组中TestBed.configureTestingModule得到Unexpected value 'doSomething' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation. Unexpected value 'doSomething' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.

  • 为它创建一个服务是可行的,但必须为每个导入的函数创建服务感觉很愚蠢

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

import * as helper from './helper';

在您的 it() 中,您可以监视 helper 对象并返回请求的值:

spyOn(helper, 'doSomething').and.returnValue({});

模拟外部函数是不可能的,但是您可以执行以下操作,该操作可以正常工作。

import { doSomething } from './helper';

@Component({
    ...
})
export class AppComponent {
    const doSomethingRef = doSomething; 
    test() {
        const data = this.doSomethingRef(1);
        return data.something ? 1: 2;
    }
}

现在,因为我们可以模拟doSomethingRef

describe('AppComponent ', () => {
  let appComponent: AppComponent ;
  beforeEach(() => {
    TestBed.configureTestingModule({});
    appComponent= TestBed.inject(AppComponent);
  });

  it('should allow mocking', () => {
    (appComponent as AppComponent).doSomethingRef = jasmine.createSpy('doSomethingRef ').and.returnValue(1);
    expect(guard.test()).toEqual(1);
  });
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM