我正在为 Nestjs 应用程序进行 e2e 测试,其中一个模块正在使用 https://github.com/deligenius/aws-sdk-v3-nest 模块。我一直在嘲笑它。
我不知道如何模拟注入附件模块的 S3 客户端。运行测试时,它实际上使用真实的S3客户端。
这是我到目前为止所拥有的。
// app.module
@Module({
imports: [
AttachmentsModule,
],
controllers: [],
providers: [],
})
export class AppModule {
}
// attachment module
@Module({
controllers: [],
providers: [
S3fileService,
],
imports: [
AwsSdkModule.registerAsync({
clientType: S3Client,
imports: [ConfigModule],
useFactory: async (configService: ConfigService<EnvConfigs, true>) => {
const awsConfigs = configService.get('awsConfigs', { infer: true });
return new S3Client({
region: awsConfigs.region,
});
},
inject: [ConfigService],
}),
],
exports: [S3fileService],
})
export class AttachmentsModule {}
// S3fileService service
@Injectable()
export class S3fileService {
constructor(
@InjectAws(S3Client) private readonly s3: S3Client, // I want to mock this S3Client
) {
console.log(s3);// during test this is real s3 instance
}
}
// my test
import { S3Client } from '@aws-sdk/client-s3';
import { mockClient } from 'aws-sdk-client-mock';
const s3Mock = mockClient(S3Client);
describe('InvoicesController (e2e)', () => {
let app: INestApplication;
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
providers: [/// this is not working
{
provide: S3Client,
useValue: s3Mock,
},
],
})
.overrideProvider(S3Client) // this is not working
.useValue(s3Mock)
.compile();
app = moduleFixture.createNestApplication();
await app.init();
});
});
原来我需要使用正确的 DI 令牌。我已在 @InjectAws(S3Client) private readonly s3: S3Client 之类的服务中导入了 S3Client,并在后台生成了类似 AWS_SDK_V3_MODULE#S3Client# 之类的令牌。 o 我不确定这是正确的方法,但它有效!
.overrideProvider('AWS_SDK_V3_MODULE#S3Client#') // this is working
.useValue(s3Mock)