首页 > 解决方案 > TestBed 上的提供者和声明有什么区别

问题描述

我是 Angular 的新手。我在学习 Angular 的 TDD 时有一些问题。

据我所知,Testbed.configureTestingModule 的 TestModuleMetadata 是一个对象,它具有提供者、声明和导入等,就像 @ngModule 的对象一样。

所以我想如果我想测试组件,我所要做的就是将组件放入 TestModuleMetaData 的提供者中。

但这带来了错误,例如“没有 SomeComponent 的提供者!” 和'StaticInjectorError [SomeComponent]:'

之后,我将 someComponent 从声明中移至提供者,并且它工作正常。

为什么会这样?我认为声明是要在模块上使用的组件的数组,而提供程序是用于服务的。

我错了吗??

    import { TestBed } from "@angular/core/testing";
    import { WelcomeComponent } from "./welcome.component";
    import { UserService } from "../user.service";

    describe("WelcomeComponent", () => {
      let comp: WelcomeComponent;
      let userService: UserService;

      beforeEach(() => {
        // This work correctly
        TestBed.configureTestingModule({
          providers: [UserService, WelcomeComponent]
        });

        // This doesn't work
        // TestBed.configureTestingModule({
        //   declarations: [WelcomeComponent],
        //   providers: [UserService]
        // });

        comp = TestBed.get(WelcomeComponent);
        userService = TestBed.get(UserService);
      });

      it("should not have welcome message after construction", () => {
        expect(comp.welcome).toBeUndefined();
      });

      it("should welcome logged in user after Angular calls ngOnInit", () => {
        comp.ngOnInit();
        expect(comp.welcome).toContain(userService.user.name);
      });

      it("should ask user to log in if not logged in after ngOnInit", () => {
        userService.isLoggedIn = false;
        comp.ngOnInit();
        expect(comp.welcome).not.toContain(userService.user.name);
        expect(comp.welcome).toContain("log in");
      });
    });

标签: angularkarma-jasmineangular-test

解决方案


在您的测试代码中,您有:

comp = TestBed.get(WelcomeComponent);

那是为了查找已经实例化的服务。相反,您需要创建组件:

comp = TestBed.createComponent(WelcomeComponent);

推荐阅读