Jest : TypeError: Cannot read property 'length' of undefined

enter image description here

Why it object.anonymous

package.json:

package.json:
{ "name": "SmartConverter", "version": "1.0.0", "main": "./src/js/main.js", "scripts": { "test": "jest --coverage", "build": "webpack --config ./scripts/*/webpack.config.js" }, "repository": "", "author": "raushankumarnitdgp <>", "license": "MIT", "dependencies": { "babel-cli": "^6.24.1", "babel-core": "^6.25.0", "babel-jest": "^20.0.3", "babel-loader": "^7.1.1", "babel-preset-es2015": "^6.24.1", "eslint": "^4.4.1", "jest": "^20.0.4", "jest-cli": "^20.0.4", "regenerator-runtime": "^0.10.5", "webpack": "^3.5.2" }
}

2 Answers

The anonymous keyword you see in the error stracktrace is just telling you that the error happened in an anonymous function. Anonymous functions are functions without a name, often used as callbacks but not always. For example:

function main() { myLibrary.doSomething('foo', function() { console.log('I have finished') })
}

The function passed to myLibrary.doSomething is an anonymous function. The error you are seeing seems to be happening in the phone.js file, line 20. Check where are you using .length.

I think it might be some props haven't been set yet, for instance, if you have a property called expenses inside ComponentX, but in jest file, you didn't pre-set this expenses property,

eg: <ComponentX />, forgot to pass props into this ComponentX, and Jest couldn't find where the expenses property is, expenses would be undefined, and then undefined.length definitely cause that undefined error.

How can we fix this expenses.length undefined issue?

we can do this: <ComponentX expenses={mockExpenses} />

Now, expenses.length should not be undefined, because of expenses have some data.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like