【问题标题】:React, Typescript and Jest - Why is simple test failingReact、Typescript 和 Jest - 为什么简单的测试会失败
【发布时间】:2020-01-04 13:37:04
【问题描述】:

我正在尝试将 React 与 Typescript 一起使用并使用 Jest 进行测试。

我有一个超级简单的组件,状态为空数组。

我正在尝试测试该数组是否存在并且它是空的。

我认为这一定与我设置 App.tsx 文件的方式有关。

App.tsx:

import React, { Component } from "react";

interface IState {
  gifts: string[];
}

interface IProps {}

class App extends Component<{}, IState> {
  state = {
    gifts: []
  };

  render() {
    return (
      <div>
        <h1>Gift Giver</h1>
      </div>
    );
  }
}

export default App;

App.test.tsx:

import React from "react";
import "./setUpTests";
import { shallow } from "enzyme";
import App from "./App";

const app = shallow(<App />);

it("renders correctly", () => {
  expect(app).toMatchSnapshot();
});

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

测试输出

✓ renders correctly (6ms)
  ✕ initializes the `state` with an empty list of gifts (4ms)

  ● initializes the `state` with an empty list of gifts

    expect(received).toEqual(expected) // deep equality

    Expected: []
    Received: undefined

      11 | 
      12 | it("initializes the `state` with an empty list of gifts", () => {
    > 13 |   expect(app.state.gifts).toEqual([]);
         |                           ^
      14 | });
      15 | 

      at Object.<anonymous>.it (src/App.test.tsx:13:27)

【问题讨论】:

    标签: reactjs typescript jestjs


    【解决方案1】:

    我猜你需要在constructor 中创建state 对象。

    就像下面这样:

    constructor(props:any) {
      super(props);
    
      this.state = {
        gifts: []
      };
    }
    

    在此处进一步阅读:Adding Local State to a Class

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      抱歉打错了,我才发现

      expect(app.state().gifts).toEqual([]);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-18
        • 2020-01-01
        • 2021-04-04
        • 2019-10-23
        • 2021-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多