March 26, 2021

How To Write A Jest Test For Nested Props

Hola. 👋🏾 When writing a jest test, sometimes we'd like to check for a value to be present somewhere in the file tree (aka, the array). There isn't a way to "fuzzy find" something, but if you know the nesting pattern, there's still an (UGLY) of finding what you're looking for.

Component

1import React from 'react'
2import { Text, View } from 'react-native'
3import { observer } from 'mobx-react-lite'
4import Activities from '../../stores/activitiesStore'
5import Flame from './assets/Flame'
6import styles from './styles'
7
8const Activity = () => {
9 const { count } = Activities.jumping_jacks
10
11 return (
12 <View>
13 <View>
14 <View>
15 <Text>{count}</Text>
16 </View>
17 <Text>{`jumping jacks today!`}</Text>
18 </View>
19 </View>
20 )
21}
22
23export default observer(Activity)

Test

1import React from 'react'
2import { act, create } from 'react-test-renderer'
3import Activity from '..'
4
5describe('with access to Activities values', () => {
6 const randomNumberGenerator = () => Math.floor(Math.random() * 8) + 1
7
8 beforeAll(() => {
9 Activities.jumping_jacks = {
10 count: randomNumberGenerator(),
11 }
12 })
13
14 it('renders the amount of jumping jacks to do today', () => {
15 let component
16
17 act(() => {
18 component = create(<Activity />)
19 })
20
21 const rendered = component.toTree()
22 // you may need to do a console log of "rendered" to find how your values are nested
23 const children = rendered.rendered.props.children[1].props.children
24
25 expect(rendered).toBeTruthy()
26 expect(children.length).toBe(2)
27 expect(children).toEqual(
28 expect.arrayContaining([
29 expect.objectContaining({
30 props: expect.objectContaining({
31 children: 'jumping jacks today!',
32 })
33 }),
34 expect.objectContaining({
35 props: expect.objectContaining({
36 children: expect.objectContaining({
37 props: expect.objectContaining({
38 children: Activities.jumping_jacks.count,
39 }),
40 }),
41 })
42 }),
43 ])
44 )
45 })
46})

See you next time. 🙃