Testing Components
Let's create a button component and see how we can test it.
button.component.ts
@Component({
selector: 'app-button',
template: `
<button class="{{className}}" (click)="onClick($event)">{{title}}</button>
`
})
export class ButtonComponent {
@Input() className = 'success';
@Input() title = '';
@Output() click = new EventEmitter();
onClick( $event ) {
this.click.emit($event);
}
}
button.component.spec.ts
import { ButtonComponent } from './button.component';
import { Spectator, createTestComponentFactory } from '@netbasal/spectator';
describe('ButtonComponent', () => {
let spectator: Spectator<ButtonComponent>;
const createComponent = createTestComponentFactory(ButtonComponent);
it('should have a success class by default', () => {
spectator = createComponent();
expect(spectator.query('button')).toHaveClass('success');
});
it('should set the class name according to the [className] input', () => {
spectator = createComponent();
spectator.setInput('className', 'danger');
expect(spectator.query('button')).toHaveClass('danger');
expect(spectator.query('button')).not.toHaveClass('success');
});
it('should set the title according to the [title] input', () => {
spectator = createComponent({ 'title': 'Click' });
expect(spectator.query('button')).toHaveText('Click');
});
it('should emit the $event on click', () => {
const detectChanges = false;
spectator = createComponent({}, detectChanges);
let output;
spectator.output<{ type: string }>('click').subscribe(result => output = result);
spectator.component.onClick({ type: 'click' });
spectator.detectChanges();
expect(output).toEqual({ type: 'click' });
});
});
First, you need to create a component factory by using the createTestComponentFactory()
function, passing the component class that you want to test.
The createTestComponentFactory()
returns a function that will create a fresh component in each it
block, which gives you the ability to test each functionality in an isolated environment.
The createComponent()
function takes the component inputs as the first parameter.
By default, Spectator will run the initial change detection for you. If you would like to skip it, you can pass a falsy value as the second parameter. For example:
spectator = createComponent({}, false)
The createComponent()
method returns an instance of Spectator
with the following properties:
fixture
- The tested component's fixture (the button fixture)component
- The tested component's instance (the button component)element
- The tested component's native element (the button native element)debugElement
- The tested fixture's debug element (the button debug element)
To view the available methods please see the Spectator API section.