Typescript error for React test Renderer JSON not having Children

Viewed 922

I have created an expo app with the basic typescript template as documented. Installed all the requirements needed for testing and its types.

I can run the test, and it does pass the test.

However, I am getting an error on the IDE (VS code) for the example test on the doc:

enter image description here

1 Answers

You can use Type Assertions to specify a specific type.

If the App component has a list of children:

import React, { Component } from 'react';

export default class App extends Component {
  render() {
    return (
      <>
        <div>app</div>
        <p>123</p>
      </>
    );
  }
}

You can specify the ReactTestRendererJSON[] for tree and write the test like below:

import React from 'react';
import renderer, { ReactTestRendererJSON } from 'react-test-renderer';
import App from './index';

describe('67900373', () => {
  it('should pass', () => {
    const tree = renderer.create(<App />).toJSON() as ReactTestRendererJSON[];
    console.log(tree);
    tree.forEach((node) => {
      expect(node.children?.length).toBe(1);
    });
  });
});

test result:

 PASS  examples/67900373/index.test.tsx (9.11 s)
  67900373
    ✓ should pass (28 ms)

  console.log
    [
      { type: 'div', props: {}, children: [ 'app' ] },
      { type: 'p', props: {}, children: [ '123' ] }
    ]

      at Object.<anonymous> (examples/67900373/index.test.tsx:8:13)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.006 s

If the App component only has one child

import React, { Component } from 'react';

export default class App extends Component {
  render() {
    return <div>app</div>;
  }
}

You can specify the ReactTestRendererJSON for tree and write the test like below:

import React from 'react';
import renderer, { ReactTestRendererJSON } from 'react-test-renderer';
import App from './index';

describe('67900373', () => {
  it('should pass', () => {
    const tree = renderer.create(<App />).toJSON() as ReactTestRendererJSON;
    console.log(tree);
    expect(tree.children?.length).toBe(1);
  });
});

test result:

 PASS  examples/67900373/index.test.tsx (8.113 s)
  67900373
    ✓ should pass (27 ms)

  console.log
    { type: 'div', props: {}, children: [ 'app' ] }

      at Object.<anonymous> (examples/67900373/index.test.tsx:22:13)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.817 s, estimated 10 s
Related