Angular Tests Made Easy
Spectator is written on top of the Angular Testing Framework and provides two things:
- A cleaner API for testing.
- A set of custom matchers that will help you to test DOM elements more easily.
Spectator helps you get rid of all the boilerplate grunt work, leaving you with readable, sleek and streamlined unit tests.
npm install @netbasal/spectator --save-dev
Learn about it on the docs site
Auto generate specs with the CLI
// zippy.component.ts
@Component({
selector: 'zippy',
template: `
<div class="zippy">
<div (click)="toggle()" class="zippy__title">
<span class="arrow">{{ visible ? 'Close' : 'Open' }}</span> {{title}}
</div>
<div *ngIf="visible" class="zippy__content">
<ng-content></ng-content>
</div>
</div>
`
})
export class ZippyComponent {
@Input() title;
visible = false;
toggle() {
this.visible = !this.visible;
}
}
// zippy.component.spec.ts
import { ZippyComponent } from './zippy.component';
import { createHostComponentFactory, SpectatorWithHost } from '@netbasal/spectator';
import { Component } from '@angular/core';
describe('ZippyComponent', () => {
let host: SpectatorWithHost<ZippyComponent>;
const createHost = createHostComponentFactory(ZippyComponent);
it('should display the title', () => {
host = createHost(`<zippy title="Zippy title"></zippy>`);
expect(host.query('.zippy__title')).toHaveText(( text ) => 'Zippy title');
});
it('should display the content', () => {
host = createHost(`<zippy title="Zippy title">Zippy content</zippy>`);
host.click('.zippy__title');
expect(host.query('.zippy__content')).toHaveText('Zippy content');
});
it('should display the "Open" word if closed', () => {
host = createHost(`<zippy title="Zippy title">Zippy content</zippy>`);
expect(host.query('.arrow')).toHaveText('Open');
expect(host.query('.arrow')).not.toHaveText('Close');
});
it('should display the "Close" word if open', () => {
host = createHost(`<zippy title="Zippy title">Zippy content</zippy>`);
host.click('.zippy__title');
expect(host.query('.arrow')).toHaveText('Close');
expect(host.query('.arrow')).not.toHaveText('Open');
}
);
it('should be closed by default', () => {
host = createHost(`<zippy title="Zippy title"></zippy>`);
expect('.zippy__content').not.toExist();
});
it('should toggle the content', () => {
host = createHost(`<zippy title="Zippy title"></zippy>`);
host.click('.zippy__title');
expect(host.query('.zippy__content')).toExist();
host.click('.zippy__title');
expect('.zippy__content').not.toExist();
});
});
Spectator is regularly used and maintained by Datorama.
Thanks goes to these wonderful people (emoji key):
I. Sinai π π π¨ |
Valentin Buryakov π» π€ |
Netanel Basal π» π§ |
Ben Grynhaus π π» |
Ben Elliott π» |
---|
This project follows the all-contributors specification. Contributions of any kind welcome!