Reputation: 4189
So I have this Greeter component that accept a input string and transcluded content. I got this error "The component has 1 ng-content elements, but only 0 slots were provided." when I add in ng-content tag. If I remove that, my test will be executed with no error. Here is my code and test code.
import { Component, OnInit, Input } from 'angular2/core';
@Component({
selector: 'greeter',
template: `
<h1>Hello {{name}}!</h1>
<ng-content></ng-content>
`
})
export class Greeter {
@Input() name: string;
}
Here is my test code:-
import {TestComponentBuilder, ComponentFixture, beforeEachProviders, beforeEach, inject, describe,
expect, it, injectAsync, setBaseTestProviders } from 'angular2/testing';
import {TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS} from 'angular2/platform/testing/browser'
import {Greeter} from './noob.component';
describe('Noob: component', () => {
let tcb: TestComponentBuilder;
setBaseTestProviders(TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS);
beforeEachProviders(() => [
TestComponentBuilder,
Greeter
]);
beforeEach(<any>inject([TestComponentBuilder], (_tcb: TestComponentBuilder) => {
tcb = _tcb;
}));
//specs
it('should render `John Doe!`', (done: any) => {
tcb.createAsync(Greeter).then((fixture: ComponentFixture) => {
let greeter = fixture.componentInstance,
element = fixture.nativeElement;
greeter.name = 'John Doe';
fixture.detectChanges(); //trigger change detection
expect(element.querySelector('h1').innerText).toBe('Hello John Doe!');
done();
})
.catch((e: any) => done.fail(e));
});
})
Upvotes: 4
Views: 2233
Reputation: 39268
The issue is that ng-content is not supported in root level components. When you instantiate the component in isolation in the unit test it becomes a root in that context.
The workaround is to create a simple host component for your component just for the purpose of the test.
@Component({
directives:[Greeter],
template:'<greeter></greeter>'
})
class GreeterHost{
}
Now instantiate GreeterHost
in the unit test instead so that your ng-content component no longer is a root.
With this approach you can still test greeter, but it will be tested via the new host.
Upvotes: 3