angular - Angular2 วิธีการจำลอง Activated Route Params ที่สมัครรับข้อมูล
ฉันมีคอมโพเนนต์ที่ดึงค่าจากคุณสมบัติ params ของ ActivatedRoute
ส่วนประกอบมีลักษณะดังนี้:
......
constructor(public userRegistration: UserRegistrationService, public userLogin: UserLoginService,
public router: Router, public route: ActivatedRoute) {
}
ngOnInit() {
this.verificationCode = new FormControl('', [Validators.required]);
this.confirmationCodeForm = new FormGroup({verificationCode: this.verificationCode});
//******************************
this.sub = this.route.params.subscribe(params => {
this.email = params['userId'];
});
//******************************
this.errorMessage = null;
}
......
การทดสอบจะให้ ActivatedRoute เป็น "useValue" ซึ่งจำลองคลาสนั้น การทดสอบดูเหมือนดังนี้:
describe('ConfirmRegistrationComponent', () => {
let component: ConfirmRegistrationComponent;
let fixture: ComponentFixture<ConfirmRegistrationComponent>;
let userRegistrationService: UserRegistrationService;
let userLoginService: UserLoginService;
let router: Router;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule, FormsModule, RouterTestingModule, HttpClientModule],
declarations: [ConfirmRegistrationComponent],
providers: [UserRegistrationService, UserLoginService, {
provide: ActivatedRoute,
useValue: {'params': Observable.from([{userId: 1}])}
}, ImageService, UserService, CognitoUtil,
{
provide: Router, useClass: class {
navigate = jasmine.createSpy('navigate');
}
}]
}).compileComponents();
fixture = TestBed.createComponent(ConfirmRegistrationComponent);
component = fixture.componentInstance;
userRegistrationService = TestBed.get(UserRegistrationService);
userLoginService = TestBed.get(UserLoginService);
spyOn(userLoginService, 'isAuthenticated').and.callFake(function () {
});
router = TestBed.get(Router);
fixture.detectChanges();
component.ngOnInit();
}));
it('should create', () => {
});
});
เมื่อฉันรันการทดสอบ ฉันได้รับข้อผิดพลาดดังต่อไปนี้:
Failed: Cannot read property 'subscribe' of undefined
TypeError: Cannot read property 'subscribe' of undefined
at new RouterLinkWithHref node_modules/@angular/router/esm5/router.js:6099:1)
คุณช่วยฉันหน่อยได้ไหม? ขอบคุณ!
คำตอบ #1
เมื่อใช้ RouterTestingModule คุณไม่ควรวางผู้ให้บริการ Router ในชุดผู้ให้บริการ (ให้เลือกนำเข้า RouterTestingModule หรือให้บริการ Router แต่ไม่ใช่ทั้งสองอย่าง)
นอกจากนี้ ฉันไม่แน่ใจว่าสิ่งนี้จะช่วยได้หรือไม่ แต่ฉันเคยมีปัญหาที่เกี่ยวข้องใน Angular 6 ซึ่งฉันต้องใช้ไวยากรณีนี้:
providers: [
{ provide: ActivatedRoute, useValue: {
paramMap: of( convertToParamMap( { userId: 1 } ) )
}
}
],
convertToParamMap อยู่ใน @angular/Router
คำตอบ #2
วิธีแก้ปัญหาที่ใช้ได้ผลกับฉันคือดังต่อไปนี้ (Angular 7 + Jest):
const mockActivatedRoute = {
snapshot: {
paramMap: {
get() { return '1'; }
}
}
};
และเพียงใช้มันในผู้ให้บริการ:
providers: [
{ provide: ActivatedRoute, useValue: mockActivatedRoute },
],
