【问题标题】:When executing tests, the function is not called执行测试时,不调用该函数
【发布时间】:2019-11-14 04:59:43
【问题描述】:

我有一个包含任务更新功能的控件。

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;
    }
   ....
}

我想为这个函数写一个测试。

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();
        });
        ....
    });
});

当我运行测试时,我得到一个错误。

● Todos 控制器 › TodosController() › updateTodo() 函数应该调用

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)

我的错误可能是什么?由于所有其他功能都有效。

经过一些尝试,我注意到当我删除三元运算符时,所有测试都成功通过了。我不知道这可能与什么有关。

【问题讨论】:

    标签: typescript testing jestjs


    【解决方案1】:

    由于 updateTodo 是一个异步函数,请等待其 Promise 解决,然后再“期待”响应。

    尝试类似:

    const response = await  todosController.updateTodo(data);
    //Then run your checks
    

    否则,expect 命令甚至在 promise 解决之前就被执行。

    【讨论】:

      猜你喜欢
      • 2016-08-24
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多