// This file is required by karma.conf.js and loads recursively all the .spec and framework files import 'zone.js/dist/long-stack-trace-zone'; import 'zone.js/dist/proxy.js'; import 'zone.js/dist/sync-test'; import 'zone.js/dist/jasmine-patch'; import 'zone.js/dist/async-test'; import 'zone.js/dist/fake-async-test'; import { getTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; // Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. declare const __karma__: any; declare const require: any; // Prevent Karma from running prematurely. __karma__.loaded = function () {}; // First, initialize the Angular testing environment. getTestBed().initTestEnvironment( BrowserDynamicTestingModule, platformBrowserDynamicTesting() ); // Then we find all the tests. const context = require.context('./', true, /\.spec\.ts$/); // And load the modules. context.keys().map(context); // Finally, start Karma to run the tests. __karma__.start();
// Karma configuration file, see link for more information // https://karma-runner.imtqy.com/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma'), require('karma-mocha-reporter'), ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['mocha'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
files: [{ pattern: './node_modules/@angular/material/prebuilt-themes/indigo-pink.css', included: true, watched: true }],
preprocessors: { '!(./src/api)': ['coverage'] },
beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AppComponent ], }).compileComponents(); }));
import { TestBed, async } from '@angular/core/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AppComponent ], }).compileComponents(); })); it('should create the app', async(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); })); it(`should have as title 'app'`, async(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.title).toEqual('app'); })); it('should render title in a h1 tag', async(() => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!'); })); });
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; }
<div style="text-align:center"> <h1> Welcome to {{title}}! </h1> </div>
import {Component} from '@angular/core'; import {SomeServiceService} from "./some-service.service"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; name: string; constructor(private someService: SomeServiceService) { this.name = this.someService.getName(); } }
import { TestBed, async } from '@angular/core/testing'; import { AppComponent } from './app.component'; import { SomeServiceService } from "./some-service.service"; const SomeServiceStub = { getName: () => 'some name' }; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AppComponent ], providers: [ // { provide: SomeServiceService, useValue: SomeServiceStub } ] }).compileComponents(); })); it('token should test component with dependency', () => { // root-injector // , beforeEach const someService = TestBed.get(SomeServiceService); expect(someService.getName()).toEqual('some name'); }); // , inject, , root-injector. // , it('token should test component with dependency', inject(([SomeServiceService], (someService: SomeServiceService)) => { const someService = TestBed.get(SomeServiceService); expect(someService.getName()).toEqual('some name'); })); });
@Component({ selector: 'app-login', templateUrl: 'login.component.html', styleUrls: ['login.component.less'] }) export class LoginComponent implements OnInit { loading: boolean; loginForm: FormGroup; error: any; constructor(private router: Router, private authService: UserService, private fb: FormBuilder, private ref: ChangeDetectorRef) { } ngOnInit() { this.loading = false; this.loginForm = this.fb.group({ login: [''], password: [''] }); } get login() { return this.loginForm.get('login'); } get password() { return this.loginForm.get('password'); } submit() { this.loading = true; this.submitted = true; // const data = { 'login': this.loginForm.controls['login'].value, 'password': this.loginForm.controls['password'].value }; // // - /home/main // 400 401 - this.authService.signIn(data).subscribe( resp => this.router.navigateByUrl('/home/main'), error => { this.loading = false; error.status === 401 || error.status === 400 ? this.error = {errorText: error.title} : ''; this.ref.detectChanges(); } ); } }
class MockError extends Response implements Error { name: any; message: any; } describe('LoginComponent', () => { let component: LoginComponent; let fixture: ComponentFixture<LoginComponent>; let mockBackend: MockBackend; const authUrl = 'login_url'; const testUser = { login: 'test', password: 'test' }; const successResponse = new Response( new ResponseOptions({ status: 200, body: '' }) ); const errorResponse = new MockError( new ResponseOptions({ type: ResponseType.Error, status: 401, body: JSON.stringify({ status: 401, title: 'Unauthorized', } ) }) ); beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [LoginComponent], imports: [ FormsModule, HttpModule, RouterTestingModule.withRoutes([]), ], providers: [ AuthService, {provide: XHRBackend, useClass: MockBackend} ], }).compileComponents(); mockBackend = TestBed.get(XHRBackend); mockBackend.connections.subscribe((connection: MockConnection) => { if (connection.request.method === RequestMethod.Post) { expect(connection.request.url).toEqual(authUrl); (connection.request.getBody() === JSON.stringify(testUser)) ? connection.mockRespond(successResponse) : connection.mockError(errorResponse); } else { connection.mockError(errorResponse); } }); })); beforeEach(() => { fixture = TestBed.createComponent(LoginComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should login correctly', inject([Router], (router: Router) => { const spy = spyOn(router, 'navigateByUrl'); const login = component.loginForm.controls['login']; const password = component.loginForm.controls['password']; login.setValue('test'); password.setValue('test'); fixture.detectChanges(); component.submit(); fixture.detectChanges(); const navArgs = spy.calls.first().args[0]; expect(navArgs).toEqual('/home/main'); })); it('should fail login', () => { const login = component.loginForm.controls['login']; const password = component.loginForm.controls['password']; const errorResponse = { errorText: 'Unauthorized' }; login.setValue('testad'); password.setValue('testad'); fixture.detectChanges(); component.submit(); fixture.detectChanges(); expect(component.error).toEqual(errorResponse); }); });
let mockBackend: MockBackend; const authUrl = 'login_url'; const testUser = { login: 'test', password: 'test' };
const successResponse = new Response( new ResponseOptions({ status: 200, body: '' }) ); const errorResponse = new MockError( new ResponseOptions({ type: ResponseType.Error, status: 401, body: JSON.stringify({ status: 401, title: 'Unauthorized', } ) }) );
mockBackend = TestBed.get(XHRBackend); mockBackend.connections.subscribe((connection: MockConnection) => { if (connection.request.method === RequestMethod.Post) { expect(connection.request.url).toEqual(authUrl); (connection.request.getBody() === JSON.stringify(testUser)) ? connection.mockRespond(successResponse) : connection.mockError(errorResponse); } else { connection.mockError(errorResponse); } });
it('should login correctly', inject([Router], (router: Router) => { const spy = spyOn(router, 'navigateByUrl'); const login = component.loginForm.controls['login']; const password = component.loginForm.controls['password']; login.setValue('test'); password.setValue('test'); fixture.detectChanges(); component.submit(); fixture.detectChanges(); const navArgs = spy.calls.first().args[0]; expect(navArgs).toEqual('/home/main'); }));
import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: '<child-comp [userName]="name" [userSurname]="surname"></child-comp>' }) export class ParentComponent { name = 'Some name'; surname = 'Some surname'; }
import { Input, Component} from '@angular/core'; @Component({ selector: 'child-comp', template: `<p> : {{userName}}</p> <p> : {{userSurname}}</p>` }) export class ChildComponent{ @Input() userName: string; @Input() userSurname:string; }
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {ParentComponent} from './parent.component'; import {ChildComponent} from '../child/child.component'; describe('ParentComponent', () => { let component: ParentComponent; let fixture: ComponentFixture<ParentComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ParentComponent, ChildComponent] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ParentComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { ChildComponent } from './child.component'; describe('ChildComponent', () => { let component: ChildComponent; let fixture: ComponentFixture<ChildComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ChildComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ChildComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); component.userName = 'some name'; expect(component.userName).toEqual('some name'); }); });
Source: https://habr.com/ru/post/348832/
All Articles