【问题标题】:How to test nested dependencies with angular-spectator如何使用 angular-spectator 测试嵌套依赖项
【发布时间】:2020-03-23 09:46:37
【问题描述】:

我有一个 Angular 组件正在使用依赖于另一个服务 (service2) 的服务 (service1)。

我该如何测试呢?我想模拟这两种服务。

export class service2 {
    public someFunction() {}

    constructor() {}
}


export class service1 {
    public somOtherFunction() {}
    constructor(s: Service2) {
         this.s.someFunction();
    }
}

@Component({
    selector: 'component',
    providers: [Service1],

 })
 export class component {
    constructor(private service:Service1) {
        this.service.someOtherFunction();
    }
 }   

我的测试平台是这样的。

describe('component', () => { 
    let component: Spectator<component>;
    const createComponent = createComponentFactory();

    beforeEach(() => component = createComponent());

   it('should create', () => {
     expect(component).toBeTruthy();
   });
});

相当标准,但我无法弄清楚如何模拟这些服务。 谁能帮忙??

【问题讨论】:

  • 你在用 Jasmine 和 Karma 吗?
  • Service1 是由组件本身提供的,Service2 是通过 NgModule 提供的吗?

标签: angular unit-testing jasmine angular-directive


【解决方案1】:

更新

根据我们是在组件级别还是模块级别提供服务,我们可以通过componentProviders: []providers:[] 覆盖并基本上模拟它们

尝试以下方法:

class MockedService1 {

  someOtherFunction() {
    return 'Some stubbed values';
  }
}

const createComponent = createComponentFactory({
  component: YourComponentUnderTest,
  componentProviders: [
    { provide: Service1, useClass: MockedService1 },
    // { provide: Service2, useClass: Service2 }
  ],
  imports: []
});

如果依赖层次是Component -&gt; Service1 -&gt; Service2,当我们模拟Service1时,我们不应该模拟Service2。

【讨论】:

  • 一个jez,刚刚看到服务是由组件提供的。不知道上面是否有效。但你可以快速尝试一下
  • 不,它不起作用。抱怨 Service2 的抱怨。
  • @lg.lindstrom 更新了答案。请看看它是否符合您的需求
  • 我似乎可以正常工作,但我想避免那些手动模拟每个服务。很多工作。使用框架的想法是避免额外的工作,或者:)
  • 没有让它与内置的 Jasmine 旁观者间谍一起工作。当然,您不需要每次都创建整个类。 {provide: Service1, useValue: { someOtherFunction: () =&gt; 'No cats allowed!'}} 也可以。这是一个单行。所以在我看来,就像你通过旁观者组件模拟值一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
  • 1970-01-01
  • 2021-02-01
  • 1970-01-01
  • 2017-03-06
  • 2012-04-25
相关资源
最近更新 更多