Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Angular Testing fails with Service.method is not a function
I'm trying to write a spec test for a (correctly working) Angular component, but it errors when calling a service method with:
TypeError: _this.myService.getSomeData is not a function
The service:
export class MyService implements IMyService {
constructor(private apiService: ApiHttpService) { }
public getSomeData(param1, param2) {
const serviceUrl = '../api/Admin/SomeDataGet?arg1=' + param1 + "&arg2=" + param2;
return this.apiService.get(serviceUrl);
}
public getSomeOtherData(param1) {
const serviceUrl = '../api/Admin/SomeOtherDataGet?arg1=' + param1;
return this.apiService.get(serviceUrl);
}
}
The test:
describe('Component', () => {
var myServiceSpy;
var mockedModel;
const setupSpy = () => {
myServiceSpy.someDataDetailsGet.and.callFake(() => { return Promise.resolve(mockedModel); });
};
beforeEach(async () => {
myServiceSpy = jasmine.createSpyObj('myService', ['someDataDetailsGet', 'someOtherDataGet', 'runStoredProc']);
await TestBed.configureTestingModule({
declarations: [
MyComponent,
],
providers: [
{ provide:MyService, useValue: myServiceSpy }
]
}).compileComponents();
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
setupSpy();
fixture.detectChanges();
});
});
describe('onSearch', () => {
... // it('should error' ...) tests all working correctly
it('should show success notification if search successfully gets SomeData', fakeAsync(() => {
component.input1.setValue(firstValue);
component.input2.setValue(secondValue);
component.onSearch();
expect(myServiceSpy.someDataGet).toHaveBeenCalled();
}));
});
The component's 'onSearch()':
export class MyComponent extends BaseComponent implements OnInit {
...
onSearch = () => {
this.errors.length = 0;
this.myForm.markAllAsTouched();
this.formData = this.myForm.value
if (this.myForm.valid) {
this.getSomeDataDetails(this.formData.input1.value, this.formData.input2.value);
}
}
private getSomeDataDetails = (value1, value2) => {
this.myService.getSomeData(value1, value2).then(
(response) => {
this.model = response
this.displayResponseData(this.model);
},
(response) => {
// error handling
});
};
That's probably more code than needed (but please let me know if further information is required - hopefully I transposed actual method names correctly). Looking at some other site, I expect that the problem will have something to do with the context of _this
, but I'm not sure how to access its correct context.
How do I get my test to correctly identify/call the service function?
1 comment thread