我正在处理一个角度 4 应用程序,编写单元案例,我面临以下问题。
组件.ts
ngOnInit() {
this.service.getData().subscribe(res => {
console.log(res);
this.data= JSON.parse(res._body);
this.addFormControls();
},
error => {
console.log(error);
});
}
component.spec.ts
describe('component', () => {
let userRolesService: LayoutService;
const modulesData = {
'moduleName':'Info'
}
class MockUserRolesService {
public getModulesData() {
return modulesData;
}
}
beforeEach(async(() => {
TestBed.configureTestingModule({
providers:[ {provide: LayoutService, useClass: MockUserRolesService } ]
})
.compileComponents();
}));
beforeEach(() => {
userRolesService = TestBed.get(LayoutService);
});
afterEach(() => {
userRolesService = null;
component = null;
});
it('should fetch module data', () => {
userRolesService.getData().subscribe(
result => {
expect(result).toBeTruthy();
}
);
});
});
更新了模拟服务文件的代码。你能帮我一些让它工作吗?使用模拟服务和测试床框架。你能不能请有人帮帮我......
我不知道你想嘲笑什么,但这不是你嘲笑服务的方式。
我将使用useValue
而不是useClass
,但您可以根据需要对其进行调整。
您的测试正在测试对可观察对象的订阅,并且您返回...无。
class MockUserRolesService {
public getModulesData() {
return modulesData;
}
}
您正在测试getData
而我在您的模拟中看不到它。
以下是您模拟服务的方式。
const serviceMock = {
provide: LayoutService,
useValue: {
getData: Observable.of(/* any value you want */)
}
};
TestBed.configureTestingModule({
providers:[ {provide: LayoutService, useValue: serviceMock } ]
})
编辑在单元测试中,测试功能(组件、服务)是否按预期工作。 让我们以您的ngOnInit
函数为例:
this.service.getData().subscribe(res => {
console.log(res);
this.data= JSON.parse(res._body);
this.addFormControls();
}
鉴于您编写它的方式,您的测试应涵盖以下情况:
- 我的组件是否在服务上调用
getData
? - 成功后,我的组件是否存储服务返回的数据?
- 控制台是否显示数据?
- 方法
addFormControls
叫吗?
如果你想测试它,你应该创建这个模拟:
useValue: {
getData: Observable.of({
'_body': 'my data'
})
}
现在,你必须进行测试。 由于您有一个异步调用(带有可观察量),因此您应该订阅该调用,然后调用。这是它是如何完成的。
it('should call the getData function of the service and store the data', () => {
// Spy on your service to see if it has been called, and let him process
spyOn(component['service'], 'getData').and.callThrough();
// Array notation avoid scope issues (if your variable is protected or private)
component['service'].getData().subscribe(response => {
expect(component['service'].getData).toHaveBeenCalled();
// Since you store the data in the data variable, check if it's equal to your mock value
expect(component.data).toEqual('my data');
});
});
如果要测试所有情况:
it('should call the getData function of the service and store the data', () => {
spyOn(component['service'], 'getData').and.callThrough();
spyOn(component, 'addFormControls');
spyOn(console, 'log');
component['service'].getData().subscribe(response => {
expect(component['service'].getData).toHaveBeenCalled();
expect(component.data).toEqual('my data');
expect(console.log).toHaveBeenCalledWith(response);
expect(component.addFormControls).toHaveBeenCalled();
});
});
我遇到了类似的问题,但在地图上
undefined 不是评估 arr.uniorgs 的构造函数
所以这个:
this.arr.map(aux => aux.uniorgs)
我改为:
this.arr.map(aux => aux['uniorgs'])