Angular 具有多个路由功能的 Jasmine 测试组件

Angular Jasmine testing component with multiple routing functions

我正在尝试为我的组件之一编写测试。它有两个功能可以重新路由到另一个页面。我写了两个测试,每个测试都单独工作,但出于某种原因,当它们同时在代码中时它们会发生冲突。我的间谍不会在每次测试之间重置吗?我试过制作单独的间谍,但那没有用。

县-resources.component.ts

 routeToNewPage(){
    this.router.navigate(['/admin/new-agency'], {
      state: {
        counties: this.countiesList,
        categories: this.categories
      }
    });
  }

  routeToEditPage(data:any){
    this.router.navigate(['/admin/edit-agency'], {
      state: {
        counties: this.countiesList,
        categories: this.categories,
        data: data
      }
    });
  }

component.spec.ts

describe('CountyResourcesComponent', () => {
  let component: CountyResourcesComponent;
  let fixture: ComponentFixture<CountyResourcesComponent>;
  let routerSpy = {navigate: jasmine.createSpy('navigate')};

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ CountyResourcesComponent ],
      providers: [
        ApiService, 
        {
          provide: Router, useValue: routerSpy
        }
      ],
      imports: [
        ReactiveFormsModule,
        HttpClientTestingModule,
        RouterTestingModule
      ],
      
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(CountyResourcesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

it(`should reroute page to new-agency`, () => {
    component.routeToNewPage();
    const navArgs = routerSpy.navigate.calls.first().args[0];
    expect (navArgs).toEqual(['/admin/new-agency']);
  });

  it(`should reroute page to edit-agency`, () => {
    let data = {
      junk: 12,
      junk2: 34
    }
    component.routeToEditPage(data);
    const navArgs = routerSpy.navigate.calls.first().args[0];
    expect (navArgs).toEqual(['/admin/edit-agency']);
  });


});

此错误引用了“应该将页面重新路由到编辑机构”测试中带有“expect”的行。

你是对的,你的间谍不会在每次测试之间重置。

如果我是你,我会做出以下改变(跟随!!):

// !! make a declaration here
let routerSpy: { navigate: jasmine.Spy };

  beforeEach(async () => {
    // !! assign a new object every time in the beforeEach so you get a new
    // spy for every test. Always put mocks first here so they are fresh
    // for every test.
    routerSpy = { navigate: jasmine.createSpy('navigate') };
    await TestBed.configureTestingModule({
      declarations: [ CountyResourcesComponent ],
      providers: [
        ApiService, 
        {
          provide: Router, useValue: routerSpy
        }
      ],
      imports: [
        ReactiveFormsModule,
        HttpClientTestingModule,
        // !! remove RouterTestingModule because you are mocking the `Router` already
        // RouterTestingModule
      ],
      
    })
    .compileComponents();
  });