이 컨트롤러를 단위 테스트하고 필요한 서비스 / 리포지토리를 조롱하려고합니다.
@Controller('auth')
export class AuthController {
constructor(
private readonly authService: AuthService,
private readonly usersService: UsersService,
) {}
@Post('register')
public async registerAsync(@Body() createUserModel: CreateUserModel) {
const result = await this.authenticationService.registerUserAsync(createUserModel);
// more code here
}
@Post('login')
public async loginAsync(@Body() login: LoginModel): Promise<{ accessToken: string }> {
const user = await this.usersService.getUserByUsernameAsync(login.username);
// more code here
}
}
내 단위 테스트 파일은 다음과 같습니다.
describe('AuthController', () => {
let authController: AuthController;
let authService: AuthService;
beforeEach(async () => {
const moduleRef: TestingModule = await Test.createTestingModule({
imports: [JwtModule],
controllers: [AuthController],
providers: [
AuthService,
UsersService,
{
provide: getRepositoryToken(User),
useClass: Repository,
},
],
}).compile();
authController = moduleRef.get<AuthenticationController>(AuthenticationController);
authService = moduleRef.get<AuthenticationService>(AuthenticationService);
});
describe('registerAsync', () => {
it('Returns registration status when user registration succeeds', async () => {
let createUserModel: CreateUserModel = {...}
let registrationStatus: RegistrationStatus = {
success: true,
message: 'User registered successfully',
};
jest.spyOn(authService, 'registerUserAsync').mockImplementation(() =>
Promise.resolve(registrationStatus),
);
expect(await authController.registerAsync(createUserModel)).toEqual(registrationStatus);
});
});
});
그러나 이것을 실행할 때 다음과 같은 오류가 발생합니다.
● AuthController › registerAsync › Returns registration status when user registration succeeds
Nest can't resolve dependencies of the JwtService (?). Please make sure that the argument JWT_MODULE_OPTIONS at index [0] is available in the JwtModule context.
Potential solutions:
- If JWT_MODULE_OPTIONS is a provider, is it part of the current JwtModule?
- If JWT_MODULE_OPTIONS is exported from a separate @Module, is that module imported within JwtModule?
@Module({
imports: [ /* the Module containing JWT_MODULE_OPTIONS */ ]
})
at Injector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:191:19)
at Injector.resolveComponentInstance (../node_modules/@nestjs/core/injector/injector.js:147:33)
at resolveParam (../node_modules/@nestjs/core/injector/injector.js:101:38)
at async Promise.all (index 0)
at Injector.resolveConstructorParams (../node_modules/@nestjs/core/injector/injector.js:116:27)
at Injector.loadInstance (../node_modules/@nestjs/core/injector/injector.js:80:9)
at Injector.loadProvider (../node_modules/@nestjs/core/injector/injector.js:37:9)
at Injector.lookupComponentInImports (../node_modules/@nestjs/core/injector/injector.js:223:17)
at Injector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:189:33)
● AuthController › registerAsync › Returns registration status when user registration succeeds
Cannot spyOn on a primitive value; undefined given
48 | };
49 |
> 50 | jest.spyOn(authService, 'registerUserAsync').mockImplementation(() =>
| ^
51 | Promise.resolve(registrationStatus),
52 | );
53 |
at ModuleMockerClass.spyOn (../node_modules/jest-mock/build/index.js:780:13)
at Object.<anonymous> (Authentication/authentication.controller.spec.ts:50:18)
어떻게 진행해야할지 잘 모르겠 기 때문에 도움이 필요합니다.
여기에서 몇 가지 주목할 점이 있습니다.
컨트롤러를 테스트하는 경우 두 개 이상의 수준 깊은 pf 서비스를 모의 할 필요가 없습니다.
imports
단위 테스트에서 배열 이 필요한 사용 사례가 거의 없어야합니다 .
대신 테스트 케이스에 대해 수행 할 수있는 작업은 다음 과 유사 합니다.
beforeEach(async () => {
const modRef = await Test.createTestingModule({
controllers: [AuthController],
providers: [
{
provide: AuthService,
useValue: {
registerUserAsync: jest.fn(),
}
},
{
provide: UserService,
useValue: {
getUserByUsernameAsync: jest.fn(),
}
}
]
}).compile();
});
이제를 사용하여 인증 서비스 및 사용자 서비스 modRef.get()
를 가져 와서 나중에 모의를 추가하기 위해 변수에 저장할 수 있습니다. 다른 많은 예제가있는 이 테스트 저장소 를 확인할 수 있습니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다