我的组件中有此服务,其方法之一被动态调用
@Input methodName: string;
constructor(
private readonly testService: testService
) {
}
loadData() {
this.testService[this.methodName]().subscribe();
}
一世
我在测试方法loadData()时遇到很多麻烦,它一直告诉我this.testService [methodName]不起作用,您将如何测试这种方法?
it('should ', fakeAsync(() => {
// getData is the supposed methodName that has to be set;
testService.getData.and.returnValue(asyncData({} as any));
component.loadData();
flush();
expect(testService.getData).toHaveBeenCalled();
}));
使服务public
在组件构造函数中进行更好的测试
按照以下示例作为标准做法:
服务
@Injectable({
providedIn: 'root',
})
export class UserSvcService {
test() {
return of('test');
}
}
对于一个component.ts
@Component({
selector: 'app-user-detail',
templateUrl: './user-detail.component.html',
styleUrls: ['./user-detail.component.scss'],
})
export class UserDetailComponent implements OnInit {
name = 'test';
val :string
public constructor(public _userSvc: UserSvcService) {}
ngOnInit() {
this._userSvc[this.name]().subscribe(res =>
this.val = res
);
}
}
创建一个像这样的存根:
export class UserServiceStub {
test() {
return of('test mock');
}
}
用存根替换实际的服务为:
describe('UserDetailComponent', () => {
let component: UserDetailComponent;
let fixture: ComponentFixture<UserDetailComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [],
declarations: [UserDetailComponent],
providers: [{ provide: UserSvcService, useClass: UserServiceStub }],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UserDetailComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
expect(component.val).toBe('test mock'); // move in another "it" block
});
这应该工作。为了使您的工作方式有效,您需要创建一个spyOn
with服务作为public
1st:
it('should ', () => {
spyOn(component.testService,'getData').and.returnValue(return of({some val}));
component.loadData();
expect(component.testService.getData).toHaveBeenCalled();
});
该文章可能会更感兴趣,你
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句