简体   繁体   中英

Satisfying value of undefined in Jest test

I am trying to learn jest . I keep getting stuck with the same problems over and over again. For example,

TypeError: Cannot read property 'value' of undefined

This came from a chain of errors I cleared one at a time. In this line,

const languageName = _.findWhere(languages, { key: this.props.screenProps.user.get('language') }).value;

It started with user, get, and now value is undefined. The first 2 errors I added into my user object then passed the object as props when rendering the component. But when I add value to the user object it still says that

'value' of undefined

Test

const tree = renderer.create(
        <ProfileScreen screenProps={{ user }} />
  );

user object

module.exports = {
    id: '0052C000000gFJrQAM',
    name: 'Bob Barker',
    language: 'en',
    get: language => language,
    value: 'English (US)',
};

Question

What is the proper way to add "value" to the object so it stops throwing the error and renders the component?

According to the documentation of Underscore.js

findWhere_.findWhere(list, properties)

Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.

If no match is found, or if list is empty, undefined will be returned.

In your case, your test is making the job because findWhere didn't find any matches so it return undefined and you're trying to access value on undefined variable.

What you should do is to check if findWhere found something before accessing to the result.

const language = _.findWhere(languages, { key: this.props.screenProps.user.get('language') });

const languageName = (language !== 'undefined') ? language.value() : 'No language found');

Or if really you are sure findWhere will always return a value you should modify your test for make findWhere never undefined. That's depend a lot of where come from your languages list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM