Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v0.5.4 makes correct tests fail #778

Closed
JeremiahKoeiman opened this issue Sep 1, 2024 · 2 comments
Closed

v0.5.4 makes correct tests fail #778

JeremiahKoeiman opened this issue Sep 1, 2024 · 2 comments

Comments

@JeremiahKoeiman
Copy link

Mock repository:

import { DeepMocked, createMock } from '@golevelup/ts-jest';
---
let mockRepository: DeepMocked<Repository<Label>> = createMock<Repository<Label>>();

Example test 1:

it('should throw not found error when label is not found', async () => {
  mockRepository.preload = jest.fn().mockReturnValueOnce(undefined);

  try {
    await service.update('f91187c1-c41b-4e92-a18e-957455785b0b', {
      name: 'new title'
    });
  } catch (error) {
    expect(error).toBeInstanceOf(NotFoundException);
    expect(error).toThrow(
      expect.objectContaining({
        response: { statusCode: 404, message: 'Not Found' },
        status: 404
      })
    );
  }
});

Example test 1 console output:

should throw not found error when label is not found

expect(received).toThrow(expected)
Matcher error: received value must be a function
Received has type:  object
Received has value: [NotFoundException: Not Found]

  153 |       } catch (error) {
  154 |         expect(error).toBeInstanceOf(NotFoundException);
> 155 |         expect(error).toThrow(
      |                       ^
  156 |           expect.objectContaining({
  157 |             response: { statusCode: 404, message: 'Not Found' },
  158 |             status: 404

Example test 2:

it('should call the correct methods on createQueryBuilder adn return the archived todo', async () => {
  const id = 'b2309a6a-1f9f-479f-83c2-ecfe13a93476';
  const archivedTodo = new Todo({
    id,
    title: 'title 5',
    description: 'Description',
    priority: 2,
    completed: 0,
    deletedAt: new Date('12-5-2023')
  });

  const mockQueryBuilder = {
    where: jest.fn(),
    withDeleted: jest.fn(),
    getOne: jest.fn().mockReturnValue(archivedTodo)
  } as any;

  mockRepository.createQueryBuilder = jest.fn().mockReturnValue(mockQueryBuilder);

  await service.archive(id);

  expect(mockRepository.createQueryBuilder).toHaveBeenCalled();
  expect(mockRepository.createQueryBuilder).toHaveReturnedWith(mockQueryBuilder);
  expect(mockRepository.createQueryBuilder().where).toHaveBeenCalledWith({
    id
  });
  expect(mockRepository.createQueryBuilder().where({ id }).withDeleted).toHaveBeenCalled();
  expect(mockRepository.createQueryBuilder().where({ id }).withDeleted().getOne).toHaveBeenCalled();
  expect(mockQueryBuilder.getOne()).toBe(archivedTodo);
});

Example test 2 console output:

should call the correct methods on createQueryBuilder adn return the archived todo

TypeError: Cannot read properties of undefined (reading 'withDeleted')

  42 |     }
  43 |
> 44 |     return this.todoRepository.createQueryBuilder().where({ id }).withDeleted().getOne();
     |                                                                  ^
  45 |   }
  46 |
  47 |   public async restore(id: string): Promise<Todo> {

However, these tests are all correct. When I downgrade the package to v0.5.0 all the tests pass. That's what I've done for now. Can somebody help?

@janm3D
Copy link

janm3D commented Sep 13, 2024

Hi all. I believe I am facing a similar issue that may be related to the same root cause. I created a dummy example to highlight the issue.
Important: This issue seems to be related to version 0.5.1 and onwards. With version 0.5.0 everything is working as expected.

Dummy Service which requires unit tests:

export class DummyService {
    foo(): boolean {
        return true;
    }
}

Test implementations:

it('arbitrary test case description', async () => {
    const serviceMock = createMock<DummyService>();
    jest
    .spyOn(serviceMock, 'foo')
        .mockReturnValueOnce(true)
        .mockReturnValueOnce(false)
        .mockReturnValueOnce(true);
        
    console.log(serviceMock.foo());
    console.log(serviceMock.foo());
    console.log(serviceMock.foo());
}

expected result:

true
false
true

actual result:

true

[Function: mockConstructor] {
    _isMockFunction: true,
    getMockImplementation: [Function (anonymous)],
    mock: [Getter/Setter],
    mockClear: [Function (anonymous)],
    mockReset: [Function (anonymous)],
    mockRestore: [Function (anonymous)],
    mockReturnValueOnce: [Function (anonymous)],
    mockResolvedValueOnce: [Function (anonymous)],
    mockRejectedValueOnce: [Function (anonymous)],
    mockReturnValue: [Function (anonymous)],
    mockResolvedValue: [Function (anonymous)],
    mockRejectedValue: [Function (anonymous)],
    mockImplementationOnce: [Function (anonymous)],
    withImplementation: [Function: bound withImplementation],
    mockImplementation: [Function (anonymous)],
    mockReturnThis: [Function (anonymous)],
    mockName: [Function (anonymous)],
    getMockName: [Function (anonymous)]
}

true

VonRehberg pushed a commit to VonRehberg/nestjs that referenced this issue Sep 16, 2024
@VonRehberg
Copy link
Contributor

Since I kicked off the initial change, I fixed this issue as well with #787
@underfisk @WonderPanda

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants