测试开玩笑地失败了,在jasmine中用@input传递了一个角度指令



这个晴朗的周六早上,我坐下来,目标是把我的angular 9项目变成笑话。迄今为止失败。除了JSDOM不支持DragDropEvent的ClipboardEvent(我有解决办法(之外,在Jasmine中通过的测试在Jest中失败了。

以下是我正在测试的内容:

@Directive({
selector: '[evAutoTab]'
})
export class EvAutoTabDirective {
@Input('evAutoTab') target: string;
@HostListener('keyup') onKeyup() {
this.moveFocus();
}
constructor(private el: ElementRef) {
}
private moveFocus() {
const maxLen = this.el.nativeElement.getAttribute('maxlength');
const len = this.el.nativeElement.value.length;
// console.log(`len ${len} maxLen ${maxLen} target ${this.target}`);
if (len === parseInt(maxLen, 10)) {
const next: HTMLElement = document.querySelector('#' + this.target);
next.focus();
}
}
}

在jest和jasmine配置中,都调用了我要测试的指令,但"目标"从来都不是开玩笑设置的,所以测试失败了。evAutoTab="target"。

我相信我已经正确配置了jest(或者更确切地说,为jest正确配置了角度(

测试:

@Component({
template: `
<div>
<input evAutoTab="AutoTab1" id="AutoTab0" maxlength="4" value=""/>
<input evAutoTab id="AutoTab1" value=""/>
<input evAutoTab="AutoTab4" id="AutoTab2" maxlength="2" value=""/>
</div>
<div>
<input evAutoTab id="AutoTab3" value=""/>
<input evAutoTab id="AutoTab4" value=""/>
<input evAutoTab id="AutoTab5" value=""/>
</div>
`
})
class TestComponent {
constructor() {
}
}
describe('EvAutoTabDirective', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
TestComponent,
EvAutoTabDirective
]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
it('should move focus from third element skipping to fifth', () => {
const debugEl: HTMLElement = fixture.debugElement.nativeElement;
const autoTab2: HTMLInputElement = debugEl.querySelector('#AutoTab2');
const autoTab4: HTMLInputElement = debugEl.querySelector('#AutoTab4');
const focusSpy = spyOn({
here: () => {
}
}, 'here');
// verify setup
autoTab2.focus();
expect(document.activeElement.id).toEqual('AutoTab2');
// act
autoTab2.value = '19';
autoTab2.dispatchEvent(new Event('keyup'));
fixture.detectChanges();
expect(document.activeElement.id).toEqual('AutoTab4');
});
});

有什么建议吗?

所以用jest测试我需要第二个fixture。detectChanges((;

fixture.detectChanges();
fixture.detectChanges();
expect(document.activeElement.id).toEqual('AutoTab4');

现在它起作用了。

给玩笑第二次机会

为了响应您的回答,您可以通过在创建测试组件时设置自动检测更改来避免此detectChanges调用两次

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
providers:[{ provide: ComponentFixtureAutoDetect, useValue: true }] //<= SET AUTO HERE
})
.compileComponents();
}));

最新更新