TypeError: Cannot read property 'forEach' of undefined jest

Viewed 1146

I am encountering this error on my test suite run using jest although it is working as is on react compile. Please see error and code screenshot below.

enter image description here

3 Answers

You can use conditional chaining to check if data.tags is not void and forEach method exists on tags property to avoid errors. But make sure you're passing correct data.

const tags:any = [];

data.tags?.forEach?.((tag: Tag) => {
 tags.push({ label: tag.label, value: tag.value})
}

You are testing for !== null but your data has no property tags (and react/typescript does not know this). So your data.tags is evaluated to undefined.

if(data.tags !== null && data.tags !== undefined) {

or

if(data.tags) {

would work.

When you have an of undefined issue always look to the left, so here you have can't read forEach of undefined... i.e. there is no forEach property on undefined... undefined as in the Javascript undefined.

So what is forEach called on - tags. So there is no tags property on data aka its undefined. Your better placed to use something like;

if (data.tags) {
   data.tags.forEach((tag: Tag) => {
     tags.push({ label: tag.label, value: tag.value})
   }
}

if (data.tags) will check null, undefined and false.

Related