Jest: How to mock an ES6 class that is a named export in Jest?

Created on 4 Jun 2019  路  5Comments  路  Source: facebook/jest

I asked this question on StackOverflow but did not get an answer. I think it is difficult enough that a solution should be documented in the docs.

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.

Most helpful comment

Are you looking for this?

-return jest.fn().mockImplementation(() => {
-    return {query: mockQuery};
-});
+return {
+    abc: jest.fn().mockImplementation(() => {
+       return {query: mockQuery};
+    })
+};

(Assuming that the export name is abc)

All 5 comments

Are you looking for this?

-return jest.fn().mockImplementation(() => {
-    return {query: mockQuery};
-});
+return {
+    abc: jest.fn().mockImplementation(() => {
+       return {query: mockQuery};
+    })
+};

(Assuming that the export name is abc)

Seriously? That easy? Thanks so much, @jeysal - that worked like a charm!

If you still feel that it should be documented (not sure if it is yet) and find a good place to put it, feel free to send a PR :)

It is definitely not documented, spent half a day looking at the docs and googling! Heads down right now, but I will send a PR when I a some more time.

@jeysal - I've tried your solution, but it didn't work.
Here's my code:
_The class:_

export class MyClass {
  constructor(options) {
    // some logic
  }
}

_The mock:_

import { MyClass } from './my-class';
jest.mock('./my-class', () => ({ MyClass: jest.fn() }));
console.log(MyClass);

_The log results:_

function () {
              return fn.apply(this, arguments);
            }

I do not get a jest.fn() objet and hence do not have mockImplementation etc.
Can you tell why?

Was this page helpful?
0 / 5 - 0 ratings