0
votes

I'm new on Angular. I have some questions during studying TDD of Angular.

As far as I know, TestModuleMetadata for Testbed.configureTestingModule is a object which has provider, declarations and imports and so on like the object for @ngModule.

So I thought if I want to test component, All I have to do is putting component into providers of TestModuleMetaData.

But that brought error like 'No provider for SomeComponent!' and 'StaticInjectorError[SomeComponent]: '

after that I move someComponent to providers from declarations and It worked properly.

Why does that happens? I thought Declarations is Array for components you want to use on Module, and providers is for Service.

Do I get wrong??

    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");
      });
    });
1
You got it right, declarations is for components and providers is for services. Could you post the code that is giving you trouble?Daniel
Yes I just posted my code, Thanks for your interestingJangchun Lee

1 Answers

0
votes

In your test code you have:

comp = TestBed.get(WelcomeComponent);

That is for finding services that are already instantiated. Instead, you need to create your component:

comp = TestBed.createComponent(WelcomeComponent);