1
votes

Jest documentation clearly shows how to manually mock an ES6 class when it is a default export. For example, here's a class that is exported as default:

class QueryService {
    query(queryText: string): Promise<any> {
        // ----- Query the API -----

        // ----- Return the result -----
        return Promise.resolve({
            data: {
                ticker: 'GOOG',
                name: 'Alphabet Company'
            }
        });
    }
}

export default QueryService;

And it is mocked as follows:

const mockQuery = jest.fn();
jest.mock('./QueryService', () => {
    return jest.fn().mockImplementation(() => {
        return {query: mockQuery};
    });
});

However how do I mock this class if it was a named export? I couldn't figure this out!

Here's my full repo with this example.

2

2 Answers

0
votes

Answered here: https://github.com/facebook/jest/issues/8532.

Summary:

const mockQuery = jest.fn();
jest.mock('./QueryService', () => {
    return {
        QueryService: jest.fn().mockImplementation(() => {
            return { query: mockQuery };
        })
    };
});
0
votes

For a class you want to use the spyOn() function which is specifically designed for classes