[英]Property 'xxx' does not exist on type 'Readonly<{}>'
I'm trying to write tests for a React Typescript component. 我正在尝试为React Typescript组件编写测试。 App.tsx:
App.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;
and a test for that component. 并对该组件进行测试。 App.test.tsx:
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 }]); }); });
I'm getting a following error: 我收到以下错误:
(14,24): Property 'gifts' does not exist on type 'Readonly<{}>'.
In App.test.tsx I cannot seem to find any details regarding that. 在App.test.tsx中,我似乎找不到任何详细信息。 The app is bootstrapped with create-react-app with ts version of the scripts.
该应用程序将使用带有ts版本脚本的create-react-app进行引导。 The tests pass but when I try starting the app, it throws that error.
测试通过了,但是当我尝试启动应用程序时,它将引发该错误。 What need to be done?
需要做什么?
Because <App/>
has the generic type JSX.Element
, it does not contain enough information to infer the state type in the result of shallow
(the same holds for the props & component types). 因为
<App/>
具有通用类型JSX.Element
,所以它不包含足够的信息来推断shallow
结果的状态类型(对于props和component类型也是如此)。 You can fix it by exporting IAppState
from App.tsx
and parameterizing shallow
with the component, props, & state types: 您可以通过从
App.tsx
导出IAppState
并使用组件, App.tsx
和状态类型参数化shallow
来解决此问题:
import App, {IAppState} from './App';
..
const app = shallow<App, {}, IAppState>(<App />); // {} is props type
..
This should also correctly type app.instance()
and app.setProps()
. 这也应该正确键入
app.instance()
和app.setProps()
。 Alternatively, you could choose to just test in plain JavaScript, as I'm not sure doing this in TypeScript is worth the extra effort. 另外,您可以选择仅在普通JavaScript中进行测试,因为我不确定在TypeScript中这样做是否值得付出额外的努力。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.