我正在尝试编写一个简单的TODO App的测试。
这是我的测试班:
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');
});
});
});
[当我尝试运行“创建任务”测试时,发生以下错误。
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
任何人都知道代码中的错误吗?
更新:
我将提供程序更改为{提供:getRepositoryToken(Task),useFactory:mockTaskRepository,但错误仍然存在。
这是我的TaskModule
:
@Module({
imports: [TypeOrmModule.forFeature([TaskRepository]), AuthModule],
controllers: [TasksController],
providers: [TasksService],
})
export class TasksModule {}
上面是我的TaskService
:
import { CreateTaskDto } from 'src/DTO/create-task.DTO';
import { GetTasksFiltersDto } from 'src/DTO/get-task-filter.dto';
import {
Get,
GoneException,
Injectable,
NotFoundException,
Param,
ParseIntPipe,
} from '@nestjs/common';
import { handleRetry, InjectRepository } from '@nestjs/typeorm';
import { TaskStatus } from './task-status.enum';
import { Task } from './task.entity';
import { TaskRepository } from './task.repository';
@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;
}
}
我不知道是否有影响,但我正在使用dotenv。
我的Main.ts
async function bootstrap() {
dotenvFlow.config();
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
我的AppModule
是:
@Module({
imports: [
ConfigModule.load(path.resolve(__dirname, 'config', '**/!(*.d).{ts,js}')),
TypeOrmModule.forRootAsync({
useFactory: (config: ConfigService) => config.get('database'),
inject: [ConfigService],
}),
TasksModule,
AuthModule,
],
controllers: [],
providers: [],
})
export class AppModule {}
提前感谢!
如果正在寻找连接default
,则我认为仍在考虑TypeOrmModule配置。如果您有TaskEntity,请尝试将其更改为provide: TaskRepository
,而不是provide: getRepositoryToken(TaskEntity)
。这将告诉Nest覆盖@InjectRepository()
装饰器尝试提供的默认存储库。
如果不是这种情况,您认为您也可以添加TaskService
和TaskModule
类吗?