67

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__ました。ドキュメントをグローバルとして設定することによっても。

4

9 に答える 9

22

私はsetUpFiles冗談でプロパティを使用してこれを解決しました。これはjsdomの後、各テストの前に実行されます。これは私にとって完璧です。

Jest config で setupFiles を設定します。

"setupFiles": ["<rootDir>/browserMock.js"]


// browserMock.js
Object.defineProperty(document, 'currentScript', {
  value: document.createElement('script'),
});

理想的な状況は、webcomponents.js をロードして jsdom をポリフィルすることです。

于 2016-12-16T14:18:08.730 に答える
6

私のように、ドキュメントを未定義にモックしようとしている場合 (サーバー側/クライアント側のテストなど)、setupFiles を使用せずに、テスト スイート内で object.defineProperty を使用できました。

例:

beforeAll(() => {
  Object.defineProperty(global, 'document', {});
})
于 2018-02-20T10:49:09.057 に答える
6

プロパティのテスト値を定義する必要がある場合は、もう少し細かいアプローチがあります。各プロパティは個別に定義する必要があり、プロパティを作成する必要もありますwriteable

Object.defineProperty(window.document, 'URL', {
  writable: true,
  value: 'someurl'
});

参照: https://github.com/facebook/jest/issues/890

これは、Jest21.2.1とNodeを使用して私にとってはうまくいきましたv8.11.1

于 2018-05-18T22:49:27.203 に答える