【问题标题】:Instance member is not accessible Jest实例成员不可访问 Jest
【发布时间】:2020-09-10 03:42:27
【问题描述】:

第一次使用 Javascript,所以很难说出为什么会出现此错误。基本上我试图从我的类模块中获取函数,以便我可以使用它们进行测试,但是这些函数无法访问,我不明白为什么。

类(户型):

import React, {Component} from "react";
import {Card, Table, ButtonGroup, Button, InputGroup, FormControl} from "react-bootstrap";
import {Link} from "react-router-dom";
import axios from "axios";

module.exports = class HouseList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            houses: [],
        };
    }

    componentDidMount() {
        this.getAllHouses();
    }

    getAllHouses() {
        axios.get("http://localhost:8080/house")
            .then(response => response.data)
            .then((data) => {
                this.setState({houses: data});
            });
    }

    render(){
     return //etc
    }
}

测试类:

const house = require("./House");
const houseList = require("./HouseList");

const defaultHouse = {
    HouseId: "", Address: "fronttestAddress", HouseNumber: "fronttestHouseNumber", City: "fronttestCity",
};

it('createHouse', function () {
    houseList.getAllHouses() //instance member not accessible, 
                             //but if I make the function `static` I won't be able to use `setState`
    const houseAmount = houseList.houses.length; 

    house.submitHouse(defaultHouse);

    const newHouseAmount = houseList.getAllHouses.length; 
    expect(newHouseAmount).toBeGreaterThan(houseAmount);
});

我也试过import HouseList from "./Houselist",但同样的情况。为什么我无法访问HouseList-class 中的函数?

【问题讨论】:

  • 鉴于你模拟了你已经导入的两个东西,还有什么要测试的?
  • 我认为您需要先初始化您的类,然后才能访问它的成员函数。试试const houseAmount = houseList().getAllHouses().length。另一件事:您的方法 getAllHouses() 不会返回任何内容,因此 .length 将失败,因为它未在数据类型 undefined 上定义
  • @jonrsharpe 等等,所以我不应该使用jest.mock?因为我试图查找如何测试课程,而首先出现的是嘲笑。此外,当我将模拟内容注释掉时,它仍然会给出相同的错误。
  • @YashShah 哦,是的...但是我如何访问HouseList 中的houses[]?尝试添加(),但现在显示unresolved function or method getAllHouses()
  • @Zheng-rongCai, 尝试房屋 = (new houseList()).state.houses

标签: javascript reactjs jestjs


【解决方案1】:

React 组件不应该像这样进行测试。 您可以使用react-test-renderer 或最好使用Enzyme

如果你使用酶,那么只需浅层渲染组件

shallow(<HouseList {...props} />)

在此之后,componentDidMount 将自动被调用。因此,在此之前,为您的 fetch 调用添加模拟并测试是否已进行模拟调用。

要模拟通话,您可以使用Axios mock adapter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-18
    • 2014-07-19
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 2021-11-26
    相关资源
    最近更新 更多