Reputation: 23
I'm new to react and testing so maybe I'm misunderstanding the docs but I have a function that defines a const variable which is just an array of objects that has a property 'X', we'll call it. I filter this array and take the first object and look for X.
I then import it into my jest test file but it fails when I run the test, saying that Error: Uncaught [TypeError: Cannot read property 'X' of undefined].
I'm unsure as to why, as when I actually run the app it works so I'm assuming some kind of variable mocking needs to happen?
Below is my code. I've stripped out the non important parts. If anyone can guide me in the right direction please.
main.jsx
export default function main({
name, value, options, onChange, onBlur, inputRef, error, complete
}) {
const data = options.filter(name => name.uuid === value)[0].X.slice(8);
return ( blah blah blah, this works when I actually render it )
test.jsx
import main from './main';
test('Renders', () => {
const options = [
{
uuid: 'foo',
X: ['a', 'b']
}
]
const { getByText } = render(
<main
name="test"
value=""
options={options}
onChange={() => {}}
onBlur={() => {}}
/>
);
});
Upvotes: 2
Views: 11391
Reputation: 20701
.filter() returns a filtered array of elements which have passed the condition specified in the callback.
Either change your filter condition or pass in foo
as value:
<main
name="test"
value="foo"
options={options}
onChange={() => {}}
onBlur={() => {}}
/>
Otherwise, you are checking for the 0th element of an empty array, which is undefined.
Upvotes: 0
Reputation: 41
You are sending an empty value so the filter method throws an empty array and when u try to access its first element you get undefined.
That's why the error Cannot read property 'X' of undefined
Upvotes: 0
Reputation: 12807
Because you pass props value
is "" so options.filter(name => name.uuid === value)[0]
is undefined. You can update value
to fix
value="foo"
Upvotes: 2