Jest でモックされたサービスで「jest.mock() のモジュール ファクトリはスコープ外の変数を参照できません」というエラーが発生する 質問する

Jest でモックされたサービスで「jest.mock() のモジュール ファクトリはスコープ外の変数を参照できません」というエラーが発生する 質問する

サービスへの呼び出しを模擬しようとしていますが、次のメッセージが表示されて困っています。のモジュールファクトリはjest.mock()スコープ外の変数を参照することはできません。

私は ES6 構文、jest、enzyme を備えた babel を使用しています。

から -ObjectsVocabularyのリストを取得してレンダリングする、という単純なコンポーネントがあります。VocabularyEntryvocabularyService

import React from 'react';
import vocabularyService from '../services/vocabularyService';

export default class Vocabulary extends React.Component {
    render() {

        let rows = vocabularyService.vocabulary.map((v, i) => <tr key={ i } >
            <td>{ v.src }</td>
            <td>{ v.target }</td>
        </tr>);
        // render rows
    }
}

それはvocabularyServise非常に簡単です:

import { VocabularyEntry } from '../model/VocabularyEntry';

class VocabularyService {

    constructor() {
        this.vocabulary = [new VocabularyEntry("a", "b")];
    }
}
export default new VocabularyService();

vocabularyService今、テストで をモックしたいと思います:

import { shallow } from 'enzyme';
import React from 'react';
import Vocabulary from "../../../src/components/Vocabulary ";
import { VocabularyEntry } from '../../../src/model/VocabularyEntry'

jest.mock('../../../src/services/vocabularyService', () => ({

    vocabulary: [new VocabularyEntry("a", "a1")]

}));

describe("Vocabulary tests", () => {

    test("renders the vocabulary", () => {

        let $component = shallow(<Vocabulary/>);

        // expect something

    });
});

テストを実行すると、次のエラーが発生します: Vocabulary.spec.js: babel-plugin-jest-hoist: のモジュール ファクトリは、jest.mock()スコープ外の変数を参照できません。無効な変数アクセス: VocabularyEntry。

私が理解した限りでは、VocabularyEntry は宣言されていないため使用できません (jest はモック定義をファイルの先頭に移動するため)。

これを修正する方法を誰か説明してもらえますか? モック呼び出し内の参照を必要とするソリューションを見たことがありますが、クラス ファイルでこれを行う方法がわかりません。

ベストアンサー1

モックされたコンポーネントを、名前の先頭に「mock」が付いた変数に保存する必要があります。この解決策は、私が受け取ったエラー メッセージの末尾にある注記に基づいています。

注: これは、初期化されていないモック変数を防ぐための予防策です。モックが遅延要求されることが保証されている場合、 がプレフィックスとして付いた変数名mockが許可されます。

import {shallow} from 'enzyme';
import React from 'react';
import Vocabulary from "../../../src/components/Vocabulary ";
import {VocabularyEntry} from '../../../src/model/VocabularyEntry'

const mockVocabulary = () => new VocabularyEntry("a", "a1");

jest.mock('../../../src/services/vocabularyService', () => ({
    default: mockVocabulary
}));

describe("Vocabulary tests", () => {

test("renders the vocabulary", () => {

    let $component = shallow(<Vocabulary/>);

    // expect something

});

おすすめ記事