ค้นหาเว็บไซต์

typescript - การทดสอบ Angular เปลี่ยนพารามิเตอร์ 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 สำหรับการทดสอบหน่วย

ฉันรู้ว่าเราสามารถตั้งค่า ActivatedRoute ให้เป็นวัตถุที่จะถูกใช้งานตลอดการทดสอบนี้ ดังนี้:

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

แต่สิ่งนี้จะตั้งค่าค่าต่าง ๆ สำหรับทุกกรณีทดสอบ มีวิธีใดที่จะเปลี่ยน ActivatedRoute ได้อย่างไดนามิกในแต่ละกรณีทดสอบที่แตกต่างกันหรือไม่?

คำตอบ #1

คุณสามารถได้มันด้วย TestBed.get(ActivatedRoute) ในฟังก์ชัน it ของคุณถ้าคุณต้องการเก็บมันไว้ในตัวแปร คุณสามารถอัปเดตค่าได้เช่นกัน

ตั้งแต่ Karma v9.0.0 ในเวอร์ชันใหม่ล่าสุดของ Angular วิธี TestBed.get ถูกเลิกใช้แล้ว

บทความที่เกี่ยวข้อง