【问题标题】:What is the difference between providers and declarations on TestBedTestBed 上的提供者和声明有什么区别
【发布时间】:2020-05-28 17:55:08
【问题描述】:

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

【问题讨论】:

  • 你没看错,declarations 用于组件,providers 用于服务。你能发布给你带来麻烦的代码吗?
  • 是的,我刚刚发布了我的代码,感谢您的关注

标签: angular karma-jasmine angular-test


【解决方案1】:

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

comp = TestBed.get(WelcomeComponent);

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

comp = TestBed.createComponent(WelcomeComponent);

【讨论】:

  • 感谢您的回答。但是,因为我之前使用get方法获取组件,是否可以通过添加服务提供者来注入组件?
  • 我不太明白你的问题。但请记住declarations 是组件应该去的地方。如果您想要一个工作测试用例的样本,请执行ng generate component hello,它将创建一个文件hello.component.spec.ts,您可以将其用作模板。
猜你喜欢
  • 2016-12-28
  • 1970-01-01
  • 1970-01-01
  • 2015-03-20
  • 2016-12-14
  • 1970-01-01
  • 2010-11-27
相关资源
最近更新 更多