Service mocked with Jest causes “The module factory of jest.mock() is not allowed to reference any out-of-scope variables” error

前端 未结 5 1696
南方客
南方客 2020-12-08 18:53

I\'m trying to mock a call to a service but I\'m struggeling with the following message: The module factory of jest.mock() is not allowed to reference a

5条回答
  •  萌比男神i
    2020-12-08 19:30

    This is how I would solve it for your code.

    You need to store your mocked component in a variable with a name prefixed by "mock". This solution is based on the Note at the end of the error message I was getting.

    Note: This is a precaution to guard against uninitialized mock variables. If it is ensured that the mock is required lazily, variable names prefixed with mock are permitted.

    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();
    
        // expect something
    
    });
    

提交回复
热议问题