我正在创建一个用于 Nest.js 应用程序集成测试的环境。为了模拟外部依赖项,我使用自定义类覆盖
HttpService
提供程序,准确地说,是使用外观类在其自身背后隐藏更复杂的逻辑。
我需要获取对对象的引用,以便能够更改其状态,无论应用程序流程如何,并模拟某些边缘情况进行测试。
这是我的测试设置中的代码片段:
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
})
.overrideProvider(HttpService)
.useClass(HttpServiceMockFacade)
.compile();
app = moduleFixture.createNestApplication();
我已经尝试过的: 1.这不起作用,因为
Nest could not find HttpServiceMockFacade element (this provider does not exist in the current context)
const httpMockFacade = await moduleFixture.resolve<HttpServiceMockFacade>(
HttpServiceMockFacade,
);
const httpMockFacade = moduleFixture.get<HttpServiceMockFacade>(
HttpServiceMockFacade,
);
HttpServiceMockFacade
实现了比 HttpService
更多的方法并且不能直接强制转换)也没有帮助。它不会抛出错误,但我猜转换出了问题。 const httpMockFacade = moduleFixture.get<HttpService>(
HttpService,
) as unknown as HttpServiceMockFacade;
console.log(`httpMockFacade ${JSON.stringify(httpMockFacade, null, 2)}`);
// prints: httpMockFacade {}
以下到底应该如何工作?
overrideProvider(HttpService)
.useClass(HttpServiceMockFacade)
我原以为调用
HttpService
只会导致返回 HttpServiceMockFacase
。另外值得注意的是,这个 HttpServiceMockFacase
工作正常。唯一的问题在于访问对象,并且覆盖 HttpService
一切都很好。
您通常需要通过提供者令牌来
get
,而不是通过您正在注入的实际实现。
与将其注入普通模块的构造函数中的方式相同。
我通常从应用程序获取/解析,而不是直接从模块获取/解析,不确定这是否会产生影响。
const httpService = app.get(HttpService);
// or
const httpService = await app.resolve(HttpService);
// and then
httpService instanceof HttpServiceMockFacade // => should be true
然后,您可以将其类型转换为 MockFacade,或者如果您需要直接访问它,则可以执行instanceof 检查。