gpt4 book ai didi

javascript - 类型 'xxx' 上不存在属性 'Readonly<{}>'

转载 作者:行者123 更新时间:2023-11-30 11:17:27 25 4
gpt4 key购买 nike

我正在尝试为 React Typescript 组件编写测试。应用程序.tsx:

import * as React from 'react';
import { Button } from 'react-bootstrap';

interface Igift {
id: number;
}
interface IAppState {
gifts: Igift[];
}
class App extends React.Component<{}, IAppState> {
public state = {
gifts: []
};

public addGift = () => {
const { gifts } = this.state;
const ids = this.state.gifts.map(ourGift => ourGift.id);

const maxId = ids.length > 0 ? Math.max(...ids) : 0;

gifts.push({ id: maxId + 1 });

this.setState({ gifts });
};

public render() {
return (
<div>
<h2>Gift Giver</h2>
<Button className="btn-add" onClick={this.addGift}>
Add Gift
</Button>
</div>
);
}
}

export default App;

以及对该组件的测试。应用程序.test.tsx:

import { shallow } from 'enzyme';
import * as React from 'react';

import App from './App';

const app = shallow(<App />);

describe('App', () => {
it('renders correctly', () => {
expect(app).toMatchSnapshot();
});

it('initializes the `state` with an empty list of gifts', () => {
expect(app.state().gifts).toEqual([]);
});

it('adds a new gift to `state` when clicking the `add gift` button', () => {
app.find('.btn-add').simulate('click');

expect(app.state().gifts).toEqual([{ id: 1 }]);
});
});

我收到以下错误:

(14,24): Property 'gifts' does not exist on type 'Readonly<{}>'.

在 App.test.tsx 中我似乎无法找到有关此的任何详细信息。该应用程序使用带有 ts 版本脚本的 create-react-app 进行引导。测试通过了,但是当我尝试启动应用程序时,它会抛出该错误。需要做什么?

最佳答案

因为 <App/>具有通用类型 JSX.Element , 它不包含足够的信息来推断 shallow 的结果中的状态类型( Prop 和组件类型也是如此)。您可以通过导出 IAppState 来修复它来自 App.tsx和参数化 shallow使用组件、 Prop 和状态类型:

import App, {IAppState} from './App';
..
const app = shallow<App, {}, IAppState>(<App />); // {} is props type
..

这也应该正确输入 app.instance()app.setProps() .或者,您可以选择只在纯 JavaScript 中进行测试,因为我不确定在 TypeScript 中这样做是否值得付出额外的努力。

关于javascript - 类型 'xxx' 上不存在属性 'Readonly<{}>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51026443/

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