DEV Community

Discussion on: Mocking ES6 class methods with Jest!

Collapse
 
09wattry profile image
Ryan • Edited

I'm not sure if directly modifying the prototype chain makes it impossible to reset/clear the mock.

An implementation a spying on the prototype chain seems to be working better for me i.e.

import { ProductsClient } from './ProductsClient';
import { ProductManager } from './ProductManager';

it('should return the product', async () => {
  const expectedProduct = {
    id: 1,
    name: 'football',
  };

   jest.spyOn(ProductsClient.prototype, 'getById')
     .mockReturnValue(expectedProduct);

  const productManager = new ProductManager();
  const result = await productManager.getProductToManage(1); 

  expect(result.name).toBe('football'); // It passes!
});

Enter fullscreen mode Exit fullscreen mode