如何访问组件自身提供的私有服务进行单元测试

How to access private service which is provided by the component itself for unit testing

我有这个组件,它自己提供服务

@Component({
    selector: 'my-component',
    providers: [MyService],
    ...
})
export class MyComponent { 
  constructor(@Self() private service: MyService) {}
  ...
}

在单元测试期间,我注意到以下内容

beforeEach(() => {
    TestBed.configureTestingModule({
        declarations: [MyComponent],
        providers: [MyService],
    }).compileComponents();
    service = TestBed.inject(MyService);
});

service 与我的组件内的服务不是同一个实例。我想这是有道理的,但我找不到解决方案,因为对于我的测试,我需要在我的组件中访问该服务。有什么建议吗?

在那种情况下,自备不是去那里的正确方式。但是,如果您绝对必须这样做,那么您可以获得这样的访问权限:

TestBed.configureTestingModule({
    declarations: [MyComponent],
}).compileComponents();

const fixture = TestBed.createComponent(MyComponent);
service = (fixture.componentInstance as any).service;

注意 private 只是编译时,所以在运行时访问它并非不可能。不过,我仍然建议在模块级别提供服务。

正如@johnrsharpe 在上面的评论中提到的它的实现细节,因此您不必处理它。这就是我所做的,但我只是找到了一种方法。我不再需要它了,但出于教育目的,我还是会展示它:

let myService: MyService;

beforeEach(() => {
    myService = { ... };

    TestBed.configureTestingModule({
        declarations: [MyComponent],
        providers: [MyService],
    }).overrideComponent(MyComponent, {
        set: {
            providers: [
                provide: MyService, useValue: myService
            ]
        }
    });
}).compileComponents();

现在您可以使用 myService 进行模拟和监视!