angular - 如何在构造函数中使用 Jasmine 私有 ActivatedRoute 进行测试?
问题描述
这是我的组件:
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.scss']
})
export class SignUpComponent implements OnInit {
specialLink: string;
constructor(
private activatedRoute: ActivatedRoute,
) {
this.specialLink = this.activatedRoute.snapshot.params.id;
if (this.specialLink !== undefined) {
this.setSpecialSignup();
}
}
这是我的测试:
describe('SignUpComponent', () => {
let component: SignUpComponent;
let fixture: ComponentFixture<SignUpComponent>;
let ActivatedRouteMock: any;
beforeEach(async(() => {
ActivatedRouteMock = jasmine.createSpyObj('ActivatedRoute', ['snapshot']);
ActivatedRouteMock.snapshot.and.returnValue({ params: { id: "123" } });
TestBed.configureTestingModule({
declarations: [ SignUpComponent ],
imports: [ RouterTestingModule ],
providers: [
{provide: ActivatedRoute, useValue: ActivatedRouteMock}
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SignUpComponent);
component = fixture.componentInstance;
});
describe('Function calls', () => {
beforeEach(() => {
fixture.detectChanges();
});
describe('Patient Side', () => {
it('should call setSpecialSignup() when user is coming from specialLink', () => {
expect(ActivatedRouteMock.snapshot).toHaveBeenCalled();
});
我正在尝试测试在我的组件的构造函数中使用的 ActivatedRoute,但出现此错误:TypeError: Cannot read property 'id' of undefined
就像它不识别我的组件中的 ActivatedRoute,而不仅仅是在测试中。
我错过了什么 ?
解决方案
你嘲笑的方式有点奇怪,为什么不简单地嘲笑一下:
activatedRouteMock: Partial<ActivatedRoute>;
beforeEach(async(() => {
activatedRouteMock = {
snapshot: {
params: { id: 1 }
} as ActivatedRouteSnapshot,
};
TestBed.configureTestingModule({
declarations: [ SignUpComponent ],
imports: [ RouterTestingModule ],
providers: [
{ provide: ActivatedRoute, useValue: activatedRouteMock }
]
})
.compileComponents();
}));
推荐阅读
- xdebug - 为什么我的 VS Code 断点 (php) 只能在一个文件夹中工作,而不能在其他文件夹中工作?
- angular - 茉莉花试,不抓”
不是函数”错误 - laravel - Laravel Eloquent Relation 属于更新
- reactive-programming - 变换单声道
在单声道 添加一个值 - fortran - gfortran -fcheck=bounds,pointer错误报告怎么出来的
- javascript - 将已排序的 ISO 8601 日期数组拆分为 Javascript 中每天的新二维数组
- regex - Perl 正则表达式不匹配
- php - 我需要使用 PHP 将 JSON 中的请求 curl 接收到的 XML 文件保存在我的本地主机中
- xamarin.android - Xamarin Android:Recyclerview 多选它不起作用
- javascript - getElementById() 方法返回null,脚本在文档末尾指明