asvetliakov / jest-create-mock-instance

Create mock instances with Jest
MIT License
34 stars 4 forks source link

instanceOf #23

Open iulianmihai opened 3 years ago

iulianmihai commented 3 years ago

Quick question here:

I created an instance of a big class using the following code mybobject.myprop = jestCreateMockInstance.createMockInstance(GearView);

then in inside of a method that is tested there is a line const isLayout = mybobject.myprop instanceof GearView;

which returns false. Do you know what might be the problem in this case?

leosuncin commented 2 years ago

I had the same error and I solved (more like monkey-patched) using:

import { Repository } from 'typeorm';
import { createMockInstance } from 'jest-create-mock-instance';

const mockRepository = Object.assign(Object.create(Repository.prototype), createMockInstance(Repository));

expect(mockRepository instanceof Repository).toBe(true);

I don't think that's the right way, but it works 🤷

leosuncin commented 2 years ago

I finally fixed it —I think so—

import { Repository } from 'typeorm';
import { createMockInstance } from 'jest-create-mock-instance';

import { Article } from '../entities/article.entity';

const mockRepository = createMockInstance(Repository);

Object.setPrototypeOf(mockRepository, Repository.prototype);

test('should mock an instance of Repository', async () => {
  expect(mockRepository).toBeInstanceOf(Repository);

  mockRepository.findOne.mockResolvedValueOnce(new Article());

  await expect(mockRepository.findOne('a832e632-0335-4191-8469-4d849bbb72be')).resolves.toBeInstanceOf(Article);
})