首页 > 解决方案 > Angular 测试 Jasmine 和 Karma 设置 router.routerState.snapshot.url

问题描述

我有 Anagular 应用程序版本 8,测试用 Karma 和 Jasmine 编写。

我有服务:

[...]
constructor(private router: Router) {}

public setParamByUrl(): Home {
  const splitUrl = this.router.routerState.snapshot.url.split('/');
  [...]
return {
   codePostal: splitUrl[0],
   [...]
  }    
}

分析this.router.routerState.snapshot.url

但我无法设置this.router.routerState.snapshot.urlJasmine 和 Karma 文件:

describe('Routing Home', () => {
  let routingService: RoutingService;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        NgbModule,
        DfModule,
        NgSelectModule,
        NgOptionHighlightModule,
        FormsModule,
[...]
      ],
 providers:
        [
          {
            provide: ActivatedRoute,
            useValue: {
              snapshot: {
                url: 'http://localhost:8080/#/home/1X/fox?tango=MOON'
              }
            }
          }
        ],
      declarations: [],
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  }));

  beforeEach(() => {
    routingService = TestBed.get(RoutingHome);
  });

  it('Test url', () => {
    expect(routingService.setAndGetScope()).toEqual({
       codePostal: '123',
       [...]
 });

  });
});

换句话说,我希望在测试文件中设置 URL,以便测试接收在 beforeEach 部分设置的 url。

我尝试过:

 provide: ActivatedRoute,
            useValue: {
              snapshot: {
                url: 'http://localhost:8080/#/home/1X/fox?tango=MOON'
              }

但它不起作用。

标签: angularunit-testingkarma-jasmine

解决方案


推荐阅读