类型“ Readonly <{}>”上不存在属性“ xxx”

时间:2018-06-25 14:57:45

标签: javascript reactjs typescript frontend jestjs

我正在尝试为React Typescript组件编写测试。 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;

并对该组件进行测试。 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进行引导。测试通过了,但是当我尝试启动应用程序时,它将引发该错误。需要做什么?

1 个答案:

答案 0 :(得分:2)

由于<App/>具有通用类型JSX.Element,因此它没有足够的信息来推断shallow结果中的状态类型(对于道具和组件类型也是如此) 。您可以通过从IAppState导出App.tsx并使用组件,道具和状态类型对shallow进行参数化来解决此问题:

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

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