在我的代碼庫中,我呼叫了 window.open ,然后呼叫了 document.write 函式,如下所示。
public launch() {
const previewWindow = window.open('');
previewWindow.document.write(
`<iframe width="100%" height="100%" src="${this.src}"></iframe>`
);
previewWindow.document.body.setAttribute(
'style',
'padding: 0; margin: 0; overflow: hidden;'
);
}
但是當我執行單元測驗檔案時,會出現以下錯誤
TypeError: Cannot read properties of undefined (reading 'document')
我的單元測驗實作如下
it('should open url', () => {
const windowSpy = spyOn(window, 'open');
component.launch();
expect(windowSpy).toHaveBeenCalled();
});
uj5u.com熱心網友回復:
你的間諜沒有回傳任何東西。當此代碼運行時:
const previewWindow = window.open('');
previewWindow.document
previewWindow仍將為空,這就是您收到錯誤的原因。
在測驗中做這樣的事情:
const previewWindowMock = {
document: {
write() { },
body: {
setAttribute() { }
}
}
} as unknown as Window;
const windowSpy = spyOn(window, 'open').and.returnValue(previewWindowMock);
這樣,當方法運行時,您將不會有未定義的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470392.html
