gpt4 book ai didi

angular - 测试在 Jest 中失败,通过 @input 传入 jasmine 来获取 Angular Directive(指令)

转载 作者:行者123 更新时间:2023-12-02 15:20:44 25 4
gpt4 key购买 nike

在这个美好的周六早上,我坐下来,目标是让我的 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 配置中,都调用了我想要测试的指令,但 jest 中从未设置“目标”,因此测试失败。 evAutoTab="目标"。

我相信我已经正确配置了 Jest (或者更确切地说,为 Jest 正确配置了 Angular )

测试:

@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');

现在可以了。

给 Jest 第二次机会

关于angular - 测试在 Jest 中失败,通过 @input 传入 jasmine 来获取 Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60791044/

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