NagRock / ts-mockito

Mocking library for TypeScript
MIT License
974 stars 93 forks source link

Inject an instance of mock inside `thenResolve` return null #172

Closed mmarchois closed 4 years ago

mmarchois commented 4 years ago

Hi,

I have an error when i try to put an instance of mock inside a thenResolve method.

Here is my class :

export class CreateTaskCommandHandler {
  constructor(
    private readonly taskRepository: ITaskRepository,
    private readonly isTaskAlreadyExist: IsTaskAlreadyExist
  ) {}

  public async execute(command: CreateTaskCommand): Promise<TaskView> {
    const {name} = command;

    if (true === (await this.isTaskAlreadyExist.isSatisfiedBy(name))) {
      throw new TaskAlreadyExistException();
    }

    const task = await this.taskRepository.save(new Task(name));

    return new TaskView(task.getId(), task.getId()); // test failed here because task is null :((
  }
}

Here is my complete test :

// ...
beforeEach(() => {
    taskRepository = mock(TaskRepository);
    isTaskAlreadyExist = mock(IsTaskAlreadyExist);
    createdTask = mock(Task);

    handler = new CreateTaskCommandHandler(
      instance(taskRepository),
      instance(isTaskAlreadyExist)
    );
  });

it('testTaskCreatedSuccessfully', async () => {
    when(isTaskAlreadyExist.isSatisfiedBy('Task')).thenResolve(false);
    when(createdTask.getId()).thenReturn(
      '1e5fb4da-12c2-11ea-8d71-362b9e155667'
    );
    when(createdTask.getName()).thenReturn('Task');
    when(taskRepository.save(new Task('Task'))).thenResolve(
      instance(createdTask) // This doesn't seems to work, in my handler i have a null instead of my object 
    );

    expect(await handler.execute(command)).toMatchObject(
      new TaskView('1e5fb4da-12c2-11ea-8d71-362b9e155667', 'Task')
    );

    verify(isTaskAlreadyExist.isSatisfiedBy('Task')).once();
    verify(taskRepository.save(new Task('Task'))).once();
    verify(createdTask.getId()).once();
    verify(createdTask.getName()).once();
  });

Here my TaskRepository (using typeorm) :

export class TaskRepository implements ITaskRepository {
  // ...
  public save(task: Task): Promise<Task> {
    return this.repository.save(task);
  }
}

Any idea ?

mmarchois commented 4 years ago

Hello @lordrip, any solution ? :pray: Thank you.

mmarchois commented 4 years ago

Fix my problem by using deepEqual :+1:

ianw11 commented 4 years ago

Sorry to necro this thread, but can you give some more details about how you used deepEqual to fix your problem?

fider commented 2 years ago

@ianw11 & anyone else who will met such issue:

This code:

  when(taskRepository.save(new Task('Task'))).thenResolve(
    instance(createdTask) // This doesn't seems to work, in my handler i have a null instead of my object 
  );

Should compare input args with deepEqual:

import { deepEqual } from 'ts-mockito'
// ...
  when(taskRepository.save(deepEqual( new Task('Task') ))).thenResolve(
    instance(createdTask)
  );