yccteam
yccteam

Reputation: 2311

Jest es6 class mock returns undefined

I have a simple class that I want to mock and for some reason jest returns undefined.

Here's the code:

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

When I log myClass I get undefined.

If I mock without mocking the implementation, I get this:

import { MyClass as myClass } from './my-class'; 
jest.mock('./my-class');
console.log(myClass);

The code above logs: function MyClass() {return mockConstructor.apply(this,arguments);}

Which does not allow for mocking, since it is not a jest.fn() and it has none of the useful methods like mockImplementation.

What is the right way to do it?

Upvotes: 2

Views: 2618

Answers (1)

Lin Du
Lin Du

Reputation: 102257

You didn't mock the my-class module correctly. You are using Named Exports, you also need to mock this.

E.g.

my-class.ts:

export class MyClass {}

my-class.test.ts:

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

Output:

  console.log
    { [Function: mockConstructor]
      _isMockFunction: true,
      getMockImplementation: [Function],
      mock: [Getter/Setter],
      mockClear: [Function],
      mockReset: [Function],
      mockRestore: [Function],
      mockReturnValueOnce: [Function],
      mockResolvedValueOnce: [Function],
      mockRejectedValueOnce: [Function],
      mockReturnValue: [Function],
      mockResolvedValue: [Function],
      mockRejectedValue: [Function],
      mockImplementationOnce: [Function],
      mockImplementation: [Function],
      mockReturnThis: [Function],
      mockName: [Function],
      getMockName: [Function] }

Upvotes: 1

Related Questions