({ createTask: jest.-6ren">
gpt4 book ai didi

testing - NestJs - Jest - 测试 : ConnectionNotFoundError: Connection "default" was not found

转载 作者:行者123 更新时间:2023-11-28 21:36:21 26 4
gpt4 key购买 nike

我正在尝试编写一个简单的 TODO 应用测试。

这是我的服务测试类:


const mockTaskRepository = () => ({
createTask: jest.fn(),
});

describe('TasksService', () => {
let tasksService;
let taskRepository;

beforeEach(async () => {
const module = await Test.createTestingModule({
providers: [TasksService, { provide: TaskRepository, useFactory: mockTaskRepository }],
}).compile();

tasksService = await module.get<TasksService>(TasksService);
taskRepository = await module.get<TaskRepository>(TaskRepository);
});

describe('create task', () => {
it('calls taskRepository.create() and returns the result', async () => {
const createTaskDto = {
title: 'Test task',
description: 'Test desc',
};
taskRepository.createTask.mockResolvedValue('someTask');
expect(taskRepository.createTask).not.toHaveBeenCalled();
const result = await tasksService.createTask(createTaskDto);
expect(taskRepository.createTask).toHaveBeenCalledWith(createTaskDto);
expect(result).toEqual('someValue');
});
});
});

这是我的任务服务:


@Injectable()
export class TasksService {
constructor(
@InjectRepository(TaskRepository)
private taskRepository: TaskRepository,
) {}

async createTask(createTaskDto: CreateTaskDto): Promise<Task> {
const { title, description } = createTaskDto;
const task = new Task();
task.title = title;

task.description = description;
task.status = TaskStatus.IN_PROGRESS;
await task.save();

return task;
}
}

当我尝试运行“创建任务”测试时,出现以下错误。

FAIL  src/tasks/tasks.service.spec.ts
● TasksService › create task › calls taskRepository.create() and returns the result

ConnectionNotFoundError: Connection "default" was not found.

at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)
at ConnectionManager.Object.<anonymous>.ConnectionManager.get (connection/ConnectionManager.ts:40:19)
at Object.getConnection (index.ts:247:35)
at Function.Object.<anonymous>.BaseEntity.getRepository (repository/BaseEntity.ts:85:72)
at Task.Object.<anonymous>.BaseEntity.save (repository/BaseEntity.ts:50:42)
at TasksService.createTask (tasks/tasks.service.ts:35:14)
at Object.<anonymous> (tasks/tasks.service.spec.ts:69:38)

Test Suites: 1 failed, 1 passed, 2 total
Tests: 1 failed, 8 passed, 9 total

有人知道代码中的错误是什么吗?

............................................

提前致谢!

最佳答案

如果它正在寻找连接 default 那么我假设 TypeOrmModule 配置仍然被考虑在内。如果您有 TaskEntity,请尝试将其更改为 provide: getRepositoryToken(TaskEntity) 而不是 provide: TaskRepository。这将告诉 Nest 覆盖 @InjectRepository() 装饰器试图提供的默认存储库。

如果不是这种情况,您认为您还可以添加 TaskServiceTaskModule 类吗?

关于testing - NestJs - Jest - 测试 : ConnectionNotFoundError: Connection "default" was not found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58423249/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com