【问题标题】:Property 'xxx' does not exist on type 'Readonly<{}>'类型“只读<{}>”上不存在属性“xxx”
【发布时间】: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


【解决方案1】:

因为&lt;App/&gt; 具有泛型类型JSX.Element,它不包含足够的信息来推断shallow 的结果中的状态类型(同样适用于道具和组件类型)。您可以通过从App.tsx 导出IAppState 并使用组件、道具和状态类型参数化shallow 来修复它:

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

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

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 2020-05-03
    • 2018-05-13
    • 1970-01-01
    • 2020-05-08
    • 2021-02-03
    • 2020-11-01
    • 2021-12-19
    • 1970-01-01
    相关资源
    最近更新 更多