我有一个 Nestjs monorepo 应用程序,可以通过 Jest 进行工作测试。这与全局单元测试有关,该测试从 package.json 中的 Nestjs CLI 创建的配置中获取配置。
我的 storage.service.ts 使用jimp其方法之一来调整图像大小。
这具有@jimp/types依赖关系 取决于@jimp/gif取决于gifwrap。
对于在我的控制台中运行的每个测试,我都会看到以下错误:
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
at node_modules/.pnpm/gifwrap@0.9.2/node_modules/gifwrap/src/gifcodec.js:7:15
Run Code Online (Sandbox Code Playgroud)
我还使用 beforeAll() 和 afterAll() 钩子来关闭 Nestjs 模块。
笑话配置:
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": ".",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "./coverage",
"testEnvironment": "node",
"roots": [
"<rootDir>/apps/",
"<rootDir>/libs/" …Run Code Online (Sandbox Code Playgroud) 我目前正在尝试在 Google Cloud Run 上使用 Graphql 部署我的 NestJS 服务器。我还有一个作为客户端使用的 React 应用程序,托管在 Netlify 上。
但是,当我尝试运行此命令时,我在控制台中收到以下 CORS(跨源资源共享)错误:
Access to fetch at 'https://google-cloud.run.app/graphql' from origin 'https://myapp.netlify.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Run Code Online (Sandbox Code Playgroud)
我的 NestJS 应用程序配置如下:
// {cors: true}
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: …Run Code Online (Sandbox Code Playgroud) 使用事务的 mongoose 文档很简单,但是当在 Nestjs 中遵循它时,它会返回一个错误:
Connection 0 was disconnected when calling `startSession`
MongooseError: Connection 0 was disconnected when calling `startSession`
at NativeConnection.startSession
Run Code Online (Sandbox Code Playgroud)
我的代码:
const transactionSession = await mongoose.startSession();
transactionSession.startTransaction();
try
{
const newSignupBody: CreateUserDto = {password: hashedPassword, email, username};
const user: User = await this.userService.create(newSignupBody);
//save the profile.
const profile: Profile = await this.profileService.create(user['Id'], signupDto);
const result:AuthResponseDto = this.getAuthUserResponse(user, profile);
transactionSession.commitTransaction();
return result;
}
catch(err)
{
transactionSession.abortTransaction();
}
finally
{
transactionSession.endSession();
}
Run Code Online (Sandbox Code Playgroud) 给定一个通过 @InjectQueue 装饰器使用队列的 Injectable:
@Injectable()
export class EnqueuerService {
constructor (
@InjectQueue(QUEUE_NAME) private readonly queue: Queue
) {
}
async foo () {
return this.queue.add('job')
}
}
Run Code Online (Sandbox Code Playgroud)
如何测试该服务是否正确调用队列?我可以做基础脚手架:
describe('EnqueuerService', () => {
let module: TestingModule
let enqueuerService: EnqueuerService
beforeAll(async () => {
module = await Test.createTestingModule({
imports: [EnqueuerModule]
}).compile()
enqueuerService = module.get(EnqueuerService)
// Here I'd usually pull in the dependency to test against:
// queue = module.get(QUEUE_NAME)
//
// (but this doesn't work because queue is using the @InjectQueue decorator) …Run Code Online (Sandbox Code Playgroud) 我现在正在寻找解决方案几个小时:
我正在使用 NestJS 和 Nest Mailer 创建电子邮件服务。一切正常,直到我想在邮件中包含一个模板。这些模板是位于 src/mail/templates 中的 hbs 文件我知道 Nest 在编译时不包含非 TS 文件,因此:
我尝试配置 Nest-cli.json,添加了以下链接:
"compilerOptions": {
"assets":["**/*.hbs"],
"watchAssets": true,
}
Run Code Online (Sandbox Code Playgroud)
或者
"assets": [
{ "include": "**/*.hbs","watchAssets": true },
]
Run Code Online (Sandbox Code Playgroud)
我的 Nest-cli.json 文件如下所示:
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": [
{ "include": "**/*.hbs","watchAssets": true },
]
}
}
Run Code Online (Sandbox Code Playgroud)
但没有任何内容被复制到 dist 文件夹中。所以我通过修改 package.json 来解决这个问题,添加了一个 cp 命令来手动执行此操作,但我认为这不是正确的方法...有人知道在资产中包含一些非 TS 文件吗
PS:hbs 用于车把(邮件模板)
感谢您的帮助 :)
我在 NestJS 中看到两种模拟服务进行单元测试的方法,第一种与我们在实际模块中定义提供程序相同,例如:
const module = await Test.createTestingModule({
providers: [
UserService,
{
provide: getRepositoryToken(User),
useValue: mockUsersRepository,
}
],
}).compile();
Run Code Online (Sandbox Code Playgroud)
以及方法的另一种方式overrideProvider。如下:
const module = await Test.createTestingModule({
imports: [UserModule]
})
.overrideProvider(getRepositoryToken(User))
.useValue(mockUsersRepository)
.compile();
Run Code Online (Sandbox Code Playgroud)
有什么不同?
在 NestJS 中使用和包描述 DTO 类时,有没有办法设置装饰器的执行顺序?class-validatorclass-transformer
当 的值foo设置为时,以下代码会失败null并出现错误:
需要一个字符串,但收到一个 null
@IsOptional()
@IsString()
@IsByteLength(1, 2048)
@Transform(({ value }) => validator.trim(value))
@Transform(({ value }) => validator.stripLow(value))
foo: string;
Run Code Online (Sandbox Code Playgroud)
即使我有一个isString装饰器应该检查是否确实传递了一个字符串,并且必须已经失败而不将执行传递给装饰@Transform器,但它并没有失败。
decorator typescript class-validator nestjs class-transformer
我有两个实体,一个是car,另一个是carAvailability
import { Entity, Column, PrimaryGeneratedColumn, OneToMany } from 'typeorm';
import { CarAvailability } from 'src/car-availabilitys/car-availability.entity';
@Entity('cars')
export class Car {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany(() => CarAvailability, (carAvailability) => carAvailability.car, {
eager: true,
cascade: true,
})
availabilities: CarAvailability[];
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试添加一项根据可用性查询和过滤汽车的服务。在我的服务中尝试了两种方法:
具有 repo 函数的方法 1:
async test () {
const startDateTime = '2012-04-24 02:25:43.511';
return await this.repo.find({
relations: ['availabilities'],
where: {
availabilities: {
start_date_time: startDateTime
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
使用查询生成器的方法 2:
async test () { …Run Code Online (Sandbox Code Playgroud) 我正在尝试从 NestJS(Node.JS 环境)中的 Postgres 数据库获取数据记录。
我使用 Prisma 作为 TypeScript 中的对象关系映射器 (ORM)。
在获取“ADMIN”用户记录时,我无法选择要使用的查询。
请有人解释一下在获取数据记录时使用“select”与使用“include”之间的区别(我是 Prisma 初学者 - 请保持简单)。
提前致谢!
代码如下所示:
使用包括:
const users = await prisma.user.findMany({
where: {
role: 'ADMIN',
},
include: {
posts: true,
},
})
Run Code Online (Sandbox Code Playgroud)
使用选择:
const users = await prisma.user.findMany({
where: {
role: 'ADMIN',
},
select: {
posts: true,
},
})
Run Code Online (Sandbox Code Playgroud) 在这部分文档中,并未清楚地解释所有防护用法的用例:
NestJS 文档 - 基于声明的授权
CaslAbilityFactory 为这些用例实现:
并仅解释了最琐碎的用例:
用户对所有内容拥有只读访问权限
它通过以下控制器方法进行了演示:
@Get()
@UseGuards(PoliciesGuard)
@checkPolicies((ability: AppAbility) => ability.can(Action.Read, Article))
findAll() {
return this.articlesService.findAll();
}
Run Code Online (Sandbox Code Playgroud)
但我应该如何注释一个方法来检查第三个或第四个用例:
已发布的文章无法删除:
(article.isPublished === true)
@Delete()
@UseGuards(PoliciesGuard)
@checkPolicies(?????????????????????????????)
delete(@Body() article: Article) {
return this.articlesService.delete(article.id);
}
Run Code Online (Sandbox Code Playgroud)
有可能吗?对于此要求,@checkPolicies 中声明的 PoliciesGuard 或处理程序应该能够访问方法参数。
如何从守卫访问控制器方法参数?
当然,如果您直接从控制器方法调用ability.can(...),则有一个解决方案:
@Delete()
@UseGuards(SomeGuards but NOT PoliciesGuard)
delete(@Body() article: Article) {
const ability = this.caslAbilityFactory.createForUser(<<user from request>>);
if (!ability.can(Action.Delete, article)) {
throw new UnauthorizedException();
}
return this.articlesService.delete(article.id);
}
Run Code Online (Sandbox Code Playgroud)
但这个解决方案不符合原来的声明模式。
nestjs ×10
typescript ×4
jestjs ×2
node.js ×2
postgresql ×2
casl ×1
compilation ×1
cors ×1
decorator ×1
graphql ×1
javascript ×1
mailer ×1
mocking ×1
mongoose ×1
netlify ×1
prisma ×1
typeorm ×1
unit-testing ×1