TestBed 上的提供者和声明有什么区别

What is the difference between providers and declarations on TestBed

我是 Angular 的新手。 我在学习 Angular.

的 TDD 过程中遇到了一些问题

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

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

但这带来了像 'No provider for SomeComponent!' 和 'StaticInjectorError[SomeComponent]: '

这样的错误

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

为什么会这样? 我认为 Declarations 是你想在 Module 上使用的组件的 Array,而 providers 是服务。

我是不是记错了??

    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");
      });
    });

在你的测试代码中你有:

comp = TestBed.get(WelcomeComponent);

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

comp = TestBed.createComponent(WelcomeComponent);