我开始在Angular中测试组件和服务。我观看了有关复数视力的课程,并尝试遵循以下观点:https ://codecraft.tv/courses/angular/unit-testing/mocks-and-spies/但是,测试组件方法存在问题。不幸的是,我找不到解决方案,因此决定向您寻求帮助。
我的服务:
@Injectable()
export class MyService {
private config: AppConfig;
constructor(private apiService: ApiService, private configService: ConfigurationService) {
this.config = configService.instant<AppConfig>();
}
public get(name: string, take: number = 10, skip: number = 0, params?:any): Observable<any> {
return this.apiService.post(`${this.config.baseUrl}/${name}/paginated?take=${take}&skip=${skip}`, params);
}
}
我的组件:
@Component({
selector: 'my',
templateUrl: './my.component.html',
styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit {
@Input("customerId") customerId: string;
items: CustomerItem[] = [];
public pagingInfo: PagingMetadata = {
itemsPerPage: 5,
currentPage: 1,
totalItems: 0
};
constructor(private service: MyService) { }
ngOnInit() {
if (this.customerId) {
this.updateItems();
}
}
updateItems() {
let skip = (this.pagingInfo.currentPage - 1) * this.pagingInfo.itemsPerPage;
let take = this.pagingInfo.itemsPerPage;
this.service.get("customer", take, skip, { customerId: this.customerId }).subscribe(result => {
this.items = result.entities;
this.pagingInfo.totalItems = result.total;
}, (error) => {
console.log(error.message);
});
}
}
我的my.component.spec.ts测试文件:
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
let mockService;
let ITEMS = [
{
"title": "test",
"id": "5e188d4f-5678-461b-8095-5dcffec0855a"
},
{
"title": "test2",
"id": "5e188d4f-1234-461b-8095-5dcffec0855a"
}
]
beforeEach(async(() => {
mockService = jasmine.createSpyObj(['get']);
TestBed.configureTestingModule({
imports: [NgxPaginationModule, RouterTestingModule],
declarations: [MyComponent],
providers: [
{ provide: MyService, useValue: mockService }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
// works fine
it('should create', () => {
expect(component).toBeTruthy();
});
// works fine
it('should NOT call updateItems method on initialization', () => {
component.ngOnInit();
let spy = spyOn(component, 'updateItems').and.callThrough();
expect(spy).not.toHaveBeenCalled();
});
// works fine
it('should call updateItems method on initialization', () => {
component.customerId = "1";
let spy = spyOn(component, 'updateItems').and.callFake(() => { return null });
component.ngOnInit();
expect(spy).toHaveBeenCalled();
});
// gives error
it('should update items', () => {
component.pagingInfo.currentPage = 1;
component.pagingInfo.itemsPerPage = 10;
component.customerId = "1";
mockService.get.and.returnValue(of(ITEMS));
component.updateItems();
expect(component.items).toBe(ITEMS);
});
});
3个前一个测试工作正常,但是在最后一个-更新项目时出现错误:
预期未定义为[Object({“ title”:“ test”,“ id”:“ 5e188d4f-5678-461b-8095-5dcffec0855a”},{“ title”:“ test2”,“ id”:“ 5e188d4f-1234 -461b-8095-5dcffec0855a“})]
我将不胜感激任何技巧;)
非常完整的问题,谢谢!它使我可以将所有内容放到StackBlitz中,以确保我找到了正确面对的问题。:)
在该StackBlitz中,您可以看到测试全部通过了。为了使它们通过,我只做了一个更改,就更改了您从中返回的值mockService.get
,如下所示:
mockService.get.and.returnValue(of({entities: ITEMS, total: 2}));
原因是您的组件期望结果对象中有一个带有项目值的“实体”键。注意-它也希望也有一个“ total”键,所以我也添加了该键,尽管您没有对此进行测试。
需要注意的另一件事,我在StackBlitz中进行了更改以进行演示。虽然您的测试全部通过了您编写的测试,但您可能不知道fixture.detectChanges()
实际执行了什么ngOnInit()
-以前使我感到困惑。为了说明这一点,我修改了您component.ngOnInit()
在一个规范中专门调用的位置以及component.updateItems()
在该规范中调用的位置,并用替换了它们fixture.detectChanges()
。双方将工作,当然很好,但我指出这一点,因为在某些测试你需要设置模拟前调用ngOnInit()
来获得有效数据,并把fixture.detectChanges()
在beforeEach()
上述所有的规格意味着它被调用每一次之前的各规格被称为。
我希望这有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句