lundi 11 novembre 2019

When executing tests, the function is not called

I have controls in which there is a task update function.

import { Controller, Post, Body, Get, Put, Delete, Param } from '@nestjs/common';
import { TodosService } from './todos.service';
import { Todos } from './todos.entity';

const message = { message: 'Entry not found' };

@Controller('todos')
export class TodosController {
    constructor(private todosService: TodosService) {}
    ....
    @Put('/update')
    async updateTodo(@Body() todos: Todos): Promise<void | { message: string }> {
        return (await this.todosService.getTodo(todos.id)) ? this.todosService.updateTodo(todos) : message;
    }
   ....
}

I want to write a test for this function.

import { Test, TestingModule } from '@nestjs/testing';
import { TodosController } from './todos.controller';
import { TodosService } from './todos.service';
import { Todos } from './todos.entity';

jest.mock('./todos.service');

describe('Todos Controller', () => {
    let todosController: TodosController;
    let todosService: TodosService;

    beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
            controllers: [TodosController],
            providers: [TodosService],
        }).compile();

        todosController = module.get<TodosController>(TodosController);
        todosService = module.get<TodosService>(TodosService);
    });

    describe('TodosController()', () => {
        ....
        it('updateTodo() function should call', () => {
            spyOn(todosService, 'updateTodo').and.callThrough();
            const data: Todos = { id: 1, title: 'New title', author: 'Name 1', date: new Date('2019-11-18') };
            todosController.updateTodo(data);
            expect(todosService.updateTodo).toHaveBeenCalled();
        });
        ....
    });
});

When I run tests, I get an error.

● Todos Controller › TodosController() › updateTodo() function should call

expect(spy).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

  55 |             const data: Todos = { id: 1, title: 'New title', author: 'Name 1', date: new Date('2019-11-18') };
  56 |             todosController.updateTodo(data);
> 57 |             expect(todosService.updateTodo).toHaveBeenCalled();
     |                                             ^
  58 |         });
  59 | 
  60 |         // it('deleteTodo() function should call', () => {

  at Object.<anonymous> (todos/todos.controller.spec.ts:57:45)

What could be my mistake? Since all other functions work

Aucun commentaire:

Enregistrer un commentaire