首页 > 解决方案 > 在其中一个测试中为 Testbed 提供者添加一个值

问题描述

如何在测试中更改 Testbed 提供者的值,而无需重新定义整个 TestBed?

describe('a test', () => {
  let router: Router;
  let route: ActivatedRoute;
  let location: Location;

  // want to be able to update this object
  let initialQueryParams: {} = {};

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule.withRoutes([
          {
            path: '',
            component: DummyComponent,
          }
        ])
      ],
      providers: [{
        provide: ActivatedRoute,
        useValue: {
          snapshot: {
          queryParams: initialQueryParams
        }
      }
    }],

    router = TestBed.inject(Router);
    route = TestBed.inject(ActivatedRoute);
    location = TestBed.inject(Location);
  });

  it('should...', () => {
    functionWhichHasRouterNavigate();

    expect(location.path()).toBe('/');
  });

  it('should do something else...', () => {
   initialQueryParams = { baz: 'qux' };
  
    functionWhichHasRouterNavigate();

    expect(location.path()).toBe('/?baz=qux');
  });

});

我尝试将 beforeEach 块中的所有内容都包装成一个 function setup = () => { ... },但这使得测试变得脆弱。价值观以某种方式相互泄漏

标签: angulartesting

解决方案


推荐阅读