gpt4 book ai didi

angular - 为 activatedRoute 数据创建测试

转载 作者:太空狗 更新时间:2023-10-29 17:43:11 28 4
gpt4 key购买 nike

我想为我的组件创建测试。我有在 ng init 中解析数据和读取数据的路由器解析器。我想为此创建测试。我如何为这段代码创建测试

    @Component({
selector: 'jhi-label-detail',
templateUrl: './label-detail.component.html'
})
export class LabelDetailComponent implements OnInit {

label: Label;

constructor(
private route: ActivatedRoute
) {
}

ngOnInit() {
this.route.data.subscribe(({label}) => {
this.label = label.body ? label.body : label;
});
}


}

路线是这样的

{
path: 'label/:id/view',
component: LabelDetailComponent,
resolve: {
label: LabelResolve
}
}

决心就是这个

@Injectable()
export class LabelResolve implements Resolve<any> {

constructor(private service: LabelService) {
}

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const id = route.params['id'] ? route.params['id'] : null;
if (id) {
return this.service.find(id);
}
return new Label();
}

}

最佳答案

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { of } from 'rxjs/observable/of';
import { Observable } from 'rxjs/Observable';

import { MyComponent } from './my-component.component';

describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
const route = ({ data: of({ label: 'hello' }) } as any) as ActivatedRoute;

beforeEach(
async(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
providers: [{ provide: ActivatedRoute, useValue: route }],
}).compileComponents();
}),
);

beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should set the label', () => {
expect(component.label).toEqual('hello');
});
});

这里要注意的重要一点是,我们在 TestBed.providers 中提供我们自己的 ActivatedRoute 实现,只有一个属性(data) 正在被我们的组件使用。

关于angular - 为 activatedRoute 数据创建测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49506086/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com