【问题标题】:Angular spectator testing: target component-level serviceAngular 旁观者测试:目标组件级服务
【发布时间】:2022-11-04 16:56:52
【问题描述】:

在我的 Angular 应用程序中,我有一个 service which is provided at a component level

@Component({
  selector: 'my-component',
  templateUrl: './my.component.html',
  providers: [MyService],
})
export class MyComponent implements OnInit, OnDestroy { ... }

我在我的 Angular 测试中使用spectator,我正在尝试以下列方式测试提供服务的组件:

const createComponent = createComponentFactory({
  component: MyComponent,
  providers: [
    // ... other services ...
    mockProvider(MyService),
  ],
  // ...
});

// ...

const spectator = createComponent();

const myService = spectator.inject(MyService);

但是,每当我尝试在myService 上模拟东西时,它都不起作用:似乎它正在获取MyService 的全局实例,而不是MyService 的组件级实例。

【问题讨论】:

    标签: angular typescript angular-test angular-unit-test angular-spectator


    【解决方案1】:

    在测试中处理组件级提供的服务时,需要采取两个重要步骤。

    1)在测试中的组件级别提供它们

    代替:

    const createComponent = createComponentFactory({
      component: MyComponent,
      providers: [
        // ... other services ...
        mockProvider(MyService),
      ],
      // ...
    });
    
    // ...
    
    const spectator = createComponent();
    

    和:

    const createComponent = createComponentFactory({
      component: MyComponent,
      providers: [
        // ... other services ...
      ],
      // ...
    });
    
    // ...
    
    const spectator = createComponent({
      mockProvider(MyService),
    });
    

    请注意,提供程序不再在createComponentFactory 中指定,而是在createComponent 中指定。

    2)从组件注入器而不是全局注入器中获取它们

    spectator.inject() 方法采用可选的第二个参数,称为fromComponentInjector(即boolean)。

    代替:

    const myService = spectator.inject(MyService);
    

    和:

    const myService = spectator.inject(MyService, true);
    

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 2021-09-16
      • 2018-01-02
      • 2019-06-15
      • 2020-12-21
      • 2017-09-15
      • 2020-03-31
      • 1970-01-01
      • 2023-01-30
      相关资源
      最近更新 更多