Я пытался протестировать свое приложение Nest. js в первый раз. Но когда я попытался запустить его, почти каждый тест, который создается клиентом по умолчанию, завершается неудачей ... Я читал об этом как о проблеме с подключением к базе данных, поэтому я попытался использовать mongodb-memory-server, но он все равно победил ' т работа. Кто-нибудь здесь, кто знает, как это исправить? Поскольку я создаю конвейер сборки, очень важно, чтобы все тесты прошли успешно ...
auth.service.ts
import { Injectable } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AuthService {
constructor(private readonly usersService: UsersService, private jwtService: JwtService) {}
async validateLoginUser(username: string, pass: string): Promise<any> {
const user = await this.usersService.findByUsernameOrEmail(username);
if (user && await user.comparePassword(pass)) {
return user;
}
return null;
}
async validateFacebookUser(profile): Promise<any> {
return await this.usersService.findByFacebookIdOrEmail(profile.id, profile.emails[0].value);
}
async validateJwtUser(payload): Promise<any> {
return await this.usersService.findByJwtPayload(payload);
}
async login(user: any) {
const payload = { username: user.username, sub: user.id };
return {
access_token: this.jwtService.sign(payload),
};
}
}
auth.service .spe c .ts
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';
import { MongooseModule } from '@nestjs/mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
describe('AuthService', () => {
let service: AuthService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
imports: [
PassportModule.register({defaultStrategy: 'jwt'}),
JwtModule.register({secret: 'secret'}),
MongooseModule.forRootAsync({
useFactory: async () => {
const mongod = new MongoMemoryServer();
const uri = await mongod.getUri();
return {
uri,
};
},
},
)],
}).compile();
service = module.get<AuthService>(AuthService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
Ошибка
Error: Nest can't resolve dependencies of the AuthService (?, JwtService). Please make sure that the argument at index [0] is available in the _RootTestModule context.
at Injector.lookupComponentInExports (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/injector.js:183:19)
at Injector.resolveComponentInstance (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/injector.js:143:33)
at resolveParam (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/injector.js:96:38)
at async Promise.all (index 0)
at Injector.resolveConstructorParams (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/injector.js:112:27)
at Injector.loadInstance (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/injector.js:78:9)
at Injector.loadProvider (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/injector.js:35:9)
at async Promise.all (index 3)
at InstanceLoader.createInstancesOfProviders (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/instance-loader.js:41:9)
at /home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/instance-loader.js:27:13
at async Promise.all (index 1)
at InstanceLoader.createInstances (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/instance-loader.js:26:9)
at InstanceLoader.createInstancesOfDependencies (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/instance-loader.js:16:9)
at TestingModuleBuilder.compile (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/testing/testing-module.builder.js:38:9)