首页 > 代码库 > [Angular] Testing @Input and @Output bindings
[Angular] Testing @Input and @Output bindings
Component:
import { Component, Input, ChangeDetectionStrategy, EventEmitter, Output } from ‘@angular/core‘;@Component({ selector: ‘stock-counter‘, changeDetection: ChangeDetectionStrategy.OnPush, template: ` <div class="stock-counter"> <div> <div (keydown)="onKeyUp($event)" (blur)="onBlur($event)" (focus)="onFocus($event)" tabindex="0"> <p>{{ value }}</p> <div tabindex="-1"> <button type="button" tabindex="-1" (click)="increment()" [disabled]="value =http://www.mamicode.com/== max"> + </button> <button type="button" tabindex="-1" (click)="decrement()" [disabled]="value =http://www.mamicode.com/== min"> - </button> </div> </div> </div> </div> `})export class StockCounterComponent { @Input() step: number = 1; @Input() min: number = 0; @Input() max: number = 100; @Output() changed = new EventEmitter<number>(); value: number = 0; focused: boolean; increment() { if (this.value < this.max) { this.value = this.value + this.step; this.changed.emit(this.value); } } decrement() { if (this.value > this.min) { this.value = http://www.mamicode.com/this.value - this.step;>
Test @Input & @Output:
import {ComponentFixture, TestBed} from ‘@angular/core/testing‘;import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from ‘@angular/platform-browser-dynamic/testing‘;import {StockCounterComponent} from ‘./stock-counter.component‘;TestBed.initTestEnvironment( BrowserDynamicTestingModule, platformBrowserDynamicTesting());describe(‘StockCounterComponent‘, () => { let component: StockCounterComponent; let fixture: ComponentFixture<StockCounterComponent>; beforeEach(() => { TestBed.configureTestingModule({ declarations: [ StockCounterComponent ] }); fixture = TestBed.createComponent(StockCounterComponent); component = fixture.componentInstance; component.value = 0; }); it(‘should not increase over the max value‘, () => { component.step = 20; component.max = 20; component.increment(); component.increment(); expect(component.value).toEqual(20); }); it(‘should not decrease below the min value‘, () => { component.step = 20; component.min = 0; component.value = 20; component.decrement(); expect(component.value).toEqual(0); component.decrement(); expect(component.value).toEqual(0); }); it(‘should call the output on a value change‘, () => { spyOn(component.changed, ‘emit‘).and.callThrough(); component.step = 10; component.increment(); expect(component.changed.emit).toHaveBeenCalledWith(10) });});
[Angular] Testing @Input and @Output bindings
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。