5

I'm staring up an Angular 5 project and it auto-generated some spec unit tests for my components and services. For those components that require Apollo I'm getting an error NullInjectorError: No provider for Apollo!

I added the Apollo module to the import and declare section like so:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ContractsDashboardComponent, Apollo ]
    })
    .compileComponents();
  }));

However now I get the error

Failed: Unexpected value 'Apollo' declared by the module 'DynamicTestModule'. Please add a @Pipe/@Directive/@Component annotation.

In the normal app I have a module GraphQLModule that calls apollo.create in the constructor. Should I mock that somehow as well?

1 Answer 1

5

If Apollo is a module, then you should import it.

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ Apollo ],
      declarations: [ ContractsDashboardComponent ]
    })
    .compileComponents();
  }));

If it isn't a module, it should be a provider, so you need to provide it :

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      providers: [ Apollo ],
      declarations: [ ContractsDashboardComponent ]
    })
    .compileComponents();
  }));

Because clearly, it isn't a component (the error requires it to have a component decorator), yet you put into the declarations.

Since your first error is NullInjectorError: No provider for Apollo!, I guess that Apollo is a service that you injected into your component, so you should use the second method, with the providing.

Sign up to request clarification or add additional context in comments.

2 Comments

so I added ApolloModule to the providers and that seems to have cleared up one error - however now I get StaticInjectorError[AuthService]: NullInjectorError: No provider for AuthService! which I'm assuming is needed by the route auth guard. I tried just adding that to declarations as well but it didn't work. Is this an easy fix or should I read up more on dependency injection with angular tests?
No, this means you have an injection in your constructor that is private authService: AuthService. To resolve this error, you need to provide your auth service by adding it to the list of providers. But since you're not testing it, you should mock it. To mock it, add this to your providers : { provide: AuthService, useValue: myMock }. Now let's say your service has only one function auth() : then myMock = { auth: () => XXX }, where XXX must be typed the same as the result of auth(). If there's not only one function, you must add every other functions / variables to myMock.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.