Tester le front avec jasmine/karma
Sources
Guide jasmine sur les spies : les spies sont le moyen recommandé par angular.io pour mocker des services
// clone it from here
git clone https://github.com/bbachi/angular-unit-testing.git
// install dependencies and start the app
npm install
npm start
Généralités
- imports : doc angular.io
import { TestBed, async } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing';
TestBed
Configures and initializes environment for unit testing and provides methods for creating components and services in unit tests. TestBed is the primary api for writing unit tests for Angular applications and libraries.
Exécuter un test dans un testBed va permettre à angular de créer un environnement pour le test. Cela signifie que s’il y a des injections de dépendances dans l’élément à tester (un service par exemple), elles vont être automatiquement injectées.
compileComponents
NO_ERRORS_SCHEMA
beforeEach
Run some shared setup before each of the specs in the describe in which it is called.
async
Wraps a test function in an asynchronous test zone. The test will automatically complete when all asynchronous calls within this zone are done. Can be used to wrap an inject call.
it
Define a single spec. A spec should contain one or more expectations that test the state of the code. A spec whose expectations all succeed will be passing and a spec with any failures will fail.
expect
Create an expectation for a spec.
Tester le component class
- structure de la classe de test
fdescribe('AppComponent', () => { let appComponent: AppComponent; beforeEach(async(() => { ... })); beforeEach(() => { ... }); it('descrption 1', () => { ... }); it('descrption 2', () => { ... }); it('descrption 3', () => { ... }); });
- setup de l’environment
beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ AppComponent ], schemas: [ NO_ERRORS_SCHEMA ] }).compileComponents(); }));
- setup de l’instance component et mock des variables
beforeEach(() => { const fixture = TestBed.createComponent(AppComponent); appComponent = fixture.debugElement.componentInstance; appComponent.itemList = [{id: 1, name: 'todolist', description: 'This is todo list app'}, {id: 2, name: 'unit test', description: 'Write unit tests'}]; });
- tests unitaires
it('should delete an item with existing item', () => { // given this item const item = {id: 1, name: 'todolist', description: 'This is todo list app'}; // execute the test case appComponent.deleteItem(item); // assertion expect(appComponent.itemList.length).toBe(1); });
Tester le component template
work in progress..
Tester les services
work in progress..
@author Josselin Tobelem