angular - 具有服务参数的组件的角度单元测试
问题描述
我是角度和单元测试的新手,我正在尝试为带有服务的组件编写一个单元测试,其中服务 url 是从@Input()
值中获取的。
cms-sonor.component.ts
export class CmsSonarComponent implements OnInit {
@Input() configParam;
sonarData;
constructor(public cmsService: CmsService) {}
ngOnInit(): void {
this.cmsService
.getData(this.configParam.url, { responseType: "text" })
.subscribe(
(resp) => {
this.sonarData = resp;
},
(err) => {
console.log(err);
}
);
}
}
cms-sonar.component.spec.ts
describe("CmsSonarComponent", () => {
let component: CmsSonarComponent;
let injector: TestBed;
let fixture: ComponentFixture<CmsSonarComponent>;
let service: CmsService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [CmsSonarComponent, SonorPipe],
providers: [
{
provide: CmsService,
useValue: {
getData: () => of({ id: 123, name: "Product" }),
},
},
],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CmsSonarComponent);
service = TestBed.get(CmsService);
component = fixture.componentInstance;
//fixture.detectChanges();
});
it("should create", () => {
expect(component).toBeDefined();
});
it("testing cms sonar ngOnInit", () => {
spyOn(service, "getData").and.callThrough();
component.ngOnInit();
fixture.detectChanges();
expect(service.getData).toHaveBeenCalledWith("/getData", "json");
expect(component.sonarData).toEqual({ id: 123, name: "Product" });
});
});
错误
TypeError: Cannot read property 'url' of undefined
你能告诉我我犯了什么错误吗?任何帮助表示赞赏。
我什至尝试使用这样的 argsspyOn(service, 'getData') .withArgs('abc')
Update-1 我能够解决上述问题,URL 试图获取输入值。
const configParam = {
url: 'visible'
};
beforeEach(() => {
fixture = TestBed.createComponent(CmsSonarComponent);
service = TestBed.get(CmsService);
component = fixture.componentInstance;
component.configParam = configParam;
//fixture.detectChanges();
});
it('testing cms sonar ngOnInit', () => {
spyOn(service, 'getData').and.callThrough();
component.ngOnInit();
fixture.detectChanges();
expect(service.getData).toHaveBeenCalledWith('visible', {
responseType: 'text'
});
expect(component.sonarData).toEqual({ id: 123, name: 'Product' });
});
但现在我得到了这个错误
Expected spy getData to have been called with:
[ 'visible', Object({ responseType: 'text' }) ]
but actual calls were:
[ 'visible' ],
[ 'visible' ]
对此的任何指南都将受到高度赞赏。
解决方案
推荐阅读
- c++ - 我需要这个数字金字塔来将特定的数字序列打印到控制台吗?
- python - Python sleep() 函数无法正常工作
- android - Kotlin 中的 Room Junction 语法
- reactjs - 为什么 react-snap 只在 SPA 应用程序中预渲染主页?
- r - 在 R 中重置种子(为一个未知值) - 快速处理循环中的问题
- java - 将按钮值切换为整数
- python - .colliderect 不工作;为什么 x 和 y 不更新?
- artifactory - 使用 docker-image-resource 向 Artifactory 推送未经授权的错误
- html - 如何将图像与文本重叠,但它们都在同一个锚标签内?
- javascript - 单击并在另一个HTML页面上插入该innerHTML时如何获取innerHTML ?