我试图为我的NestJS应用程序编写测试。它作为几个服务,包括AuthService和UserService。
我设法为AuthService编写了测试:
第一个月
import { JwtService } from '@nestjs/jwt';
import { Test } from '@nestjs/testing';
import { AuthService } from '../../src/modules/auth/auth.service';
import { UserService } from '../../src/modules/user';
describe('AuthService', () => {
let authService: AuthService;
const mockJwtService = {};
const mockUserService = {
getAll: jest.fn(),
getUnique: jest.fn(),
createUser: jest.fn(),
};
beforeEach(async () => {
// initialize a NestJS module with authService
const module = await Test.createTestingModule({
providers: [
AuthService,
{
provide: JwtService,
useValue: mockJwtService,
},
{
provide: UserService,
useValue: mockUserService,
},
],
}).compile();
authService = module.get(AuthService);
});
// it = "test case"
it('should be defined', () => {
expect(authService).toBeDefined();
});
... // MORE TESTS
});
字符串auth.service.ts
:
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { User } from '@prisma/client';
import axios from 'axios';
import { UserService } from '../user';
import { FortyTwoProfile, JwtPayload } from './auth.interface';
@Injectable()
export class AuthService {
private readonly logger = new Logger(AuthService.name);
constructor(
private jwtService: JwtService,
private userService: UserService,
) {}
... // Some functions
}
型
但是我一直在为user.service.ts
写测试:user.service.spec.ts
:
import { Test, TestingModule } from '@nestjs/testing';
import { Prisma, PrismaClient } from '@prisma/client';
import { DeepMockProxy, mockDeep } from 'jest-mock-extended';
import { PrismaService } from 'nestjs-prisma';
import { UserService } from '../../src/modules/user/user.service';
describe('UserService', () => {
let user: UserService;
let prisma: DeepMockProxy<PrismaClient>;
beforeEach(async () => {
// initialize a NestJS module with userService
const module: TestingModule = await Test.createTestingModule({
providers: [UserService, { provide: PrismaService, useValue: jest.fn() }],
})
.overrideProvider(PrismaService)
.useValue(mockDeep<PrismaClient>())
.compile();
user = module.get(UserService);
prisma = module.get(PrismaService);
});
... // MORE TESTS
});
型user.service.ts
:
import { Injectable, NotFoundException } from '@nestjs/common';
import { User } from '@prisma/client';
import { PrismaService } from '@/prisma';
import { FortyTwoProfile } from '../auth';
@Injectable()
export class UserService {
constructor(private prisma: PrismaService) {}
async getAll(): Promise<User[]> {
return this.prisma.user.findMany();
}
... // MORE FUNCTIONS
}
型
这是我的树:
├── prisma
│ ├── index.ts
│ ├── migrations
│ │ ├── 20230822155638_init
│ │ │ └── migration.sql
│ │ └── migration_lock.toml
│ └── schema.prisma
├── src
│ ├── app.middleware.ts
│ ├── app.module.ts
│ ├── config.ts
│ ├── main.ts
│ ├── modules
│ │ ├── auth
│ │ │ ├── auth.controller.ts
│ │ │ ├── auth.interface.ts
│ │ │ ├── auth.module.ts
│ │ │ ├── auth.service.ts
│ │ │ ├── ...
│ │ ├── ...
│ │ └── user
│ │ ├── index.ts
│ │ ├── user.controller.ts
│ │ ├── user.module.ts
│ │ └── user.service.ts
│ └── prisma
│ ├── index.ts
│ └── prisma.service.ts
├── test
│ ├── auth
│ │ └── auth.service.spec.ts
│ ├── jest.config.json
│ └── user
│ └── user.service.spec.ts
├── tsconfig.build.json
└── tsconfig.json
型
我得到这个错误:
● UserService › should be defined
Nest can't resolve dependencies of the UserService (?). Please make sure that the argument dependency at index [0] is available in the RootTestModule context.
Potential solutions:
- Is RootTestModule a valid NestJS module?
- If dependency is a provider, is it part of the current RootTestModule?
- If dependency is exported from a separate @Module, is that module imported within RootTestModule?
@Module({
imports: [ /* the Module containing dependency */ ]
})
12 | beforeEach(async () => {
13 | // initialize a NestJS module with userService
> 14 | const module: TestingModule = await Test.createTestingModule({
| ^
15 | providers: [UserService, { provide: PrismaService, useValue: jest.fn() }],
16 | })
17 | .overrideProvider(PrismaService)
型
谢谢你的帮助,如果我给了太多的信息,很抱歉,这是我在StackOverflow上的第一个问题。
干杯,
我尝试用PrismaService
替换{ provide: PrismaService, useValue: jest.fn() }
。
我试着只测试UserService而不测试AuthService,
我尝试了许多解决方案:Testing a NestJS Service that uses Prisma without actually accessing the database
更新1:
下面是prisma.service.ts
文件:
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
async onModuleInit() {
await this.$connect();
Logger.log('Prisma connected', 'PrismaService');
}
}
型schema.prisma
:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id String @id @default(uuid())
login String @unique
email String @unique
imageUrl String?
displayName String
firstName String
lastName String
createdAt DateTime @default(now())
}
型
更新2:
以下是我的jest.config.json
:
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"testMatch": ["<rootDir>/src/**/*spec.ts"],
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverage": true,
"moduleNameMapper": {
"^@/(.*)$": "<rootDir>/src/$1"
}
}
型
更新3:
你可以在这里重现这个问题:https://github.com/B-ki/bug_nest
1条答案
按热度按时间k5ifujac1#
package.json中的
moduleNameMapper
应该是<rootDir>/src/$1
。只有<rootdir>/$1
解析为./prisma
,这将导入./primsa/index.ts
,而./primsa/index.ts
没有Nest需要解析的值。您的意思是导入./src/prisma
,因此需要将src
添加到moduleNameMapper
的配置中