How override Provider in Angular 5 for only one test?

前端 未结 5 1191
礼貌的吻别
礼貌的吻别 2020-12-17 08:24

In one of my unit test files, I have to mock several times the same service with different mocks.

import { MyService } from \'../services/myservice.service\'         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-17 08:47

    I was facing similar problem, but in a simpler scenario, just one test(describe(...)) with multiple specifications(it(...)). The solution that worked for me was postponing the TestBed.compileComponents and the TestBed.createComponent(MyComponent) commands. Now I execute those on each individual test/specification, after calling TestBed.overrideProvider(...) when needed.

    describe('CategoriesListComponent', () => {
    ...
    beforeEach(async(() => {
      ...//mocks 
      TestBed.configureTestingModule({
        imports: [HttpClientTestingModule, RouterTestingModule.withRoutes([])],
        declarations: [CategoriesListComponent],
        providers: [{provide: ActivatedRoute, useValue: mockActivatedRoute}]
      });
    }));
    ...
    
    it('should call SetCategoryFilter when reload is false', () => {
      const mockActivatedRouteOverride = {...}
      TestBed.overrideProvider(ActivatedRoute, {useValue: mockActivatedRouteOverride });
      TestBed.compileComponents();
      fixture = TestBed.createComponent(CategoriesListComponent);
    
      fixture.detectChanges();
    
      expect(mockCategoryService.SetCategoryFilter).toHaveBeenCalledTimes(1);
    });
    

提交回复
热议问题