gpt4 book ai didi

react-native - React 测试 Renderer JSON 没有 Children 的 Typescript 错误

转载 作者:行者123 更新时间:2023-12-05 01:59:22 25 4
gpt4 key购买 nike

我已经使用记录的基本 typescript 模板创建了一个 expo 应用程序。安装了测试及其类型所需的所有要求。

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

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

enter image description here

最佳答案

您可以使用 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组件只有一个 child

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

关于react-native - React 测试 Renderer JSON 没有 Children 的 Typescript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67900373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com