Web コンポーネント プロジェクトのテストを jest で書こうとしています。私はすでにes2015プリセットでbabelを使用しています。js ファイルの読み込み中に問題が発生しました。document
オブジェクトにオブジェクトがあるコードをたどりましたcurrentScript
。しかし、テストコンテキストではそれはnull
. だから私は同じように嘲笑することを考えていました。しかしjest.fn()
、実際には同じではありません。この問題をどのように処理できますか?
jest が失敗しているコードの一部。
var currentScriptElement = document._currentScript || document.currentScript;
var importDoc = currentScriptElement.ownerDocument;
私が書いたテストケース。component.test.js
import * as Component from './sample-component.js';
describe('component test', function() {
it('check instance', function() {
console.log(Component);
expect(Component).toBeDefined();
});
});
以下は、jestによってスローされたエラーです
Test suite failed to run
TypeError: Cannot read property 'ownerDocument' of null
at src/components/sample-component/sample-component.js:4:39
更新: Andreas Köberle からの提案に従って、いくつかのグローバル変数を追加し、次のようにモックしようとしました
__DEV__.document.currentScript = document._currentScript = {
ownerDocument: ''
};
__DEV__.window = {
document: __DEV__.document
}
__DEV__.document.registerElement = jest.fn();
import * as Component from './arc-sample-component.js';
describe('component test', function() {
it('check instance', function() {
console.log(Component);
expect(Component).toBeDefined();
});
});
しかし運がない
更新:なしで上記のコードを試し__dev__
ました。ドキュメントをグローバルとして設定することによっても。