【问题标题】:Typescript error for React test Renderer JSON not having ChildrenReact 测试渲染器 JSON 没有子项的 Typescript 错误
【发布时间】:2021-06-09 18:37:16
【问题描述】:

我已经使用文档中的基本打字稿模板创建了一个 expo 应用程序。安装了测试及其类型所需的所有要求。

我可以运行测试,它确实通过了测试。

但是,我在example test on the doc 的 IDE(VS 代码)上遇到错误:

【问题讨论】:

    标签: react-native visual-studio-code jestjs expo react-test-renderer


    【解决方案1】:

    您可以使用Type Assertions 指定特定类型。

    如果App 组件有一个子列表:

    import React, { Component } from 'react';
    
    export default class App extends Component {
      render() {
        return (
          <>
            <div>app</div>
            <p>123</p>
          </>
        );
      }
    }
    

    您可以为tree 指定ReactTestRendererJSON[] 并编写如下测试:

    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);
        });
      });
    });
    

    测试结果:

     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
    

    如果App 组件只有一个孩子

    import React, { Component } from 'react';
    
    export default class App extends Component {
      render() {
        return <div>app</div>;
      }
    }
    

    您可以为tree 指定ReactTestRendererJSON 并编写如下测试:

    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);
      });
    });
    

    测试结果:

     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
    

    【讨论】:

    • 好的。现在我明白了很多。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-05-20
    • 2023-01-27
    • 2020-11-27
    • 2023-02-13
    • 2018-11-12
    • 2021-07-22
    • 2020-08-14
    • 1970-01-01
    相关资源
    最近更新 更多