针对不同的测试用例动态更改ActivatedRoute参数

针对不同的测试用例动态更改ActivatedRoute参数

本文介绍了角度测试,针对不同的测试用例动态更改ActivatedRoute参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

组件:

@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');
  });
});

使用Angular 6,Karma和Jasmine进行单元测试.

Using Angular 6, Karma and Jasmine for unit testing.

我知道我们可以将ActivatedRoute设置为将在整个测试过程中使用的对象,例如:

I know we can set ActivatedRoute to an object that will be used through out this testing, as such:

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

但这将设置所有测试用例的值.有没有一种方法可以在每个不同的测试用例中动态更改ActivatedRoute?

But this will set the values for all the test cases. Is there a way to dynamically change the ActivatedRoute in each different test case?

推荐答案

如果要将其存储在变量中,则可以使用 it 函数中的TestBed.get(ActivatedRoute)来获取它.您还可以更新值.

You can get it with TestBed.get(ActivatedRoute) in your it functions if you want to stock it in a variable. You can update value also.

这篇关于角度测试,针对不同的测试用例动态更改ActivatedRoute参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 12:50