gpt4 book ai didi

angular - 测试属性指令

转载 作者:太空狗 更新时间:2023-10-29 18:20:09 26 4
gpt4 key购买 nike

有谁知道如何在 Angular 2 中测试这个属性指令?我正在寻找一些例子,但我还没有找到。如果有人有一个例子向我展示或向我展示一种方法,它会对我有所帮助。

import { Directive, SimpleChanges, Input, OnChanges, ElementRef, Renderer} from '@angular/core';

@Directive({
selector: '[highlightData]'
})
export class HighlightDataDirective implements OnChanges {
private _highlightData: string;

@Input() set highlightData(value: string) {
const prev = this._highlightData;
this._highlightData = value;
const cur = value;
}

constructor(private _elementRef: ElementRef, private _render: Renderer) {

}

ngOnChanges(changes: SimpleChanges) {
if (changes['highlightData'] && !changes['highlightData'].isFirstChange()) {
const prev: string = changes['highlightData'].previousValue;
const cur: string = changes['highlightData'].currentValue;

if (cur !== prev) {
this._render.setElementClass(this._elementRef.nativeElement, 'animate', true);

setTimeout(() => {
this._render.setElementClass(this._elementRef.nativeElement, 'animate', false);
}, 3000);
}
}
}

}

谢谢。

最佳答案

您应该创建一个在其模板中使用该指令的宿主组件。类似的东西会起作用:

import {HighlightDataDirective} from './highlight-data.directive';
import {Component, DebugElement} from '@angular/core';
import {async, ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
import {By} from '@angular/platform-browser';

@Component({
selector: 'test',
template: '<div [highlightData]="show" (click)="show = !show">test appHighlightData</div>'
})
export class TestComponent {
show = false;
}

fdescribe('HighlightDataDirective', () => {

let fixture: ComponentFixture<TestComponent>, comp: TestComponent, debugElement: DebugElement,
element: HTMLElement;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [HighlightDataDirective, TestComponent]
});
}));

beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
comp = fixture.componentInstance;
debugElement = fixture.debugElement;
element = debugElement.nativeElement;
});

it('should apply style of click', async(() => {
fixture.detectChanges();
const directive = debugElement.query(By.directive(HighlightDataDirective));
directive.nativeElement.click();
fixture.detectChanges();
expect(directive.nativeElement.classList).toContain('animate');
}));

it('should remove style after timeout', fakeAsync(() => {
fixture.detectChanges();
tick();
const directive = debugElement.query(By.directive(HighlightDataDirective));
directive.nativeElement.click();
tick();
fixture.detectChanges();

expect(directive.nativeElement.classList).toContain('animate');
tick(3000);
expect(directive.nativeElement.classList).not.toContain('animate');
}));
});

关于angular - 测试属性指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44638136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com