Issue
I have this error:
"TypeError: Cannot read properties of undefined (reading 'id')" in my terminal.
I'm trying to test the call to Api, but the error appears.
My function:
itemToForm = () => {
this.api.send(this.component, 'get',
{ lang: 'ES', filter: { id: this.item['id'] } }
).then(resEsp => {
this.item = resEsp['data'][0];
this.api.send(this.component, 'get',
{ lang: 'EN', filter: { id: this.item['id'] } }
).then(res => {
let itemEng = res['data'][0];
let fields = this.formDef.map(register => register.filter(
field => field['register_table'].indexOf('traduction') !== -1
).map(
field => field['field_name'])
).filter(register => register.length);
fields = fields.length ? fields[0] : [];
if (itemEng) {
this.item = Object.keys(itemEng).reduce((obj, key) => {
obj[key] = this.item[key];
if (fields.indexOf(key) !== -1) {
obj[key + '_eng'] = itemEng[key];
}
return obj;
}, {});
}
if (this.item) {
this.setForm();
}
})
})
}
My spec file:
it('should call api.send', () => {
let spy1 = spyOn(api, 'send');
let item = {
id: 1,
name: 'test',
}
component.addItem(item);
component.itemToForm();
expect(spy1).toHaveBeenCalled();
});
Solution
What is happening:
The function itemToForm()
is being called before the this.item
is ready.
There are many strategies to avoid this error, a very simple one is to add a catcher at the beginning of the function, like this:
itemToForm = () => {
if(this.item === undefined) {return}
..rest of code
}
This stops the function, if the data does not exist yet.
A more elegant solution may be to go further up in your order of operations, and find who is calling itemToForm()
and ensure the data exists prior to calling.
If this does not help, or I misunderstood the issue, please comment and I'll update.
Answered By - Izzi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.