OddDev
OddDev

Reputation: 3734

No object is found when executing unit-tests with Karma in Angular CLI app

I've setup my project with Angular CLI. Also I've created my components via "ng g component NAME". This also automatically added a test-class to create my unit-tests (which is of course pretty neat).

The problem is that my tests fail hard even though I left them in the initial state. I wanted to test it out before actually writing any test. However, the test fails horribly. Not a single line is executed well.

> ng test

'app-some-selector' is not a known element:
1. If 'app-some-selector' is an Angular component, then verify that it is part of this module.

Or for example

The pipe 'myPipe' could not be found 

The above error is thrown for every single object in the specific components. If using another component via its selector, the corresponding component can not be found, if using a service like http through dependency injection, the compiler states that there is no provider for it and so on.

My project runs just fine with ng serve btw.

Upvotes: 0

Views: 74

Answers (1)

Antoine Clavijo
Antoine Clavijo

Reputation: 1305

When you create component via angular-cli, it create for you

it('should create', () => {
    expect(component).toBeTruthy();
});

This first test try to create a component and if you add a dependancie, other component for exemple, it fall.

To past this test you need to update the way you'r creating the component in the test class in the beforeEach function:

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

Here if i add a service myService in my component test dependancy injection. Like this, you can past mock object as a myService more easily to test your component.

Upvotes: 2

Related Questions