[英]NestJS: object access via string literals is disallowed in an interceptor test
I am testing an Interceptor that requires one service as a dependency.我正在测试一个需要一项服务作为依赖项的拦截器。 I need to test that a method from this service has been called.
我需要测试是否调用了该服务的方法。 The code below is working but since my dependency is private I have to call it like this:
service = interceptor['filtersService'];
下面的代码正在工作,但由于我的依赖是私有的,我必须这样称呼它:
service = interceptor['filtersService'];
. . Typescript doesn't like this and outputs a warning:
Typescript 不喜欢这样并输出警告:
object access via string literals is disallowed
不允许通过字符串文字访问 object
Is there another way to spy on a dependency?还有其他方法可以监视依赖项吗?
describe('CreateClientFilterInterceptor', () => {
const FiltersServiceMock = jest.fn<Partial<FiltersService>, []>(() => ({
async create() {
return (await SubscriberFilterMock) as Filter;
},
}));
let interceptor: CreateClientFilterInterceptor;
let service;
beforeAll(async () => {
interceptor = new CreateClientFilterInterceptor(
new FiltersServiceMock() as FiltersService,
);
service = interceptor['filtersService'];
});
it('should call create method from Filter service', async done => {
spyOn(service, 'create').and.stub();
(await interceptor.intercept(
executionContext as ExecutionContext,
callHandler,
)).subscribe(() => {
expect(service.create).toHaveBeenCalled();
done();
});
});
});
I did this workaround to get rid of the warning but it doesn't seem right to me.我做了这个解决方法来摆脱警告,但对我来说似乎不合适。
const serviceName = 'filtersService';
const service = interceptor[serviceName];
Since you are creating the service yourself, you can first create an instance, save it in your service
variable and then create the interceptor with it:由于您是自己创建服务,您可以先创建一个实例,将其保存在您的
service
变量中,然后使用它创建拦截器:
service = new FiltersServiceMock() as FiltersService;
interceptor = new CreateClientFilterInterceptor(service);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.