代码之家  ›  专栏  ›  技术社区  ›  stack247

角度测试,动态更改不同测试用例的激活路由参数

  •  3
  • stack247  · 技术社区  · 6 年前

    组成部分:

    @Component({
      selector: 'app-test',
      templateUrl: './test.component.html'
    })
    export class TestComponent implements OnInit {
      useCase: string;
    
      constructor(
        private route: ActivatedRoute,
      ) {}
    
      ngOnInit() {
        this.route.queryParams.subscribe(p => {
          if (p) {
            this.useCase = p.u;
          }
        });
      }
    }
    

    describe('TestComponent', () => {
      let component: TestComponent;
      let fixture: ComponentFixture<TestComponent>;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          imports: [
            AppModule
          ],
          providers: [
            { provide: ActivatedRoute, useValue: ??? }
          ]
        })
          .compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(TestComponent);
        component = fixture.componentInstance;
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
        expect(component.useCase).toBeFalsy();
      });
    
      it('should set useCase variable with query string value', () => {
        fixture.detectChanges();
        // Set different route.queryParams here...
        expect(component.useCase).toBe('success');
      });
    });
    

    使用Angular6、Karma和Jasmine进行单元测试。

    我知道我们可以 ActivatedRoute 对于将通过此测试使用的对象,例如:

    providers: [
      { provide: ActivatedRoute, useValue: {
        queryParams: Observable.of({id: 123})
      } }
    ]
    

    激活路由 在每个不同的测试用例中?

    1 回复  |  直到 6 年前
        1
  •  14
  •   Suresh Kumar Ariya    6 年前

    你可以用测试床得到它。在你的 如果要将其存储在变量中,则使用函数。您也可以更新值。