【发布时间】:2018-12-04 04:54:27
【问题描述】:
我正在尝试为 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;
以及对该组件的测试。 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 引导。测试通过了,但是当我尝试启动应用程序时,它会抛出该错误。需要做什么?
【问题讨论】:
-
一开始就不要这样测试。不要测试状态,这是组件的内部数据 测试其输出或更好地将业务逻辑与组件完全分离,然后直接进行单元测试,而不是通过 DOM 的布线。
标签: javascript reactjs typescript frontend jestjs