【问题标题】:Why do I get method is not a function in my jesttest?为什么我的 jesttest 中 get 方法不是函数?
【发布时间】:2017-07-28 17:35:53
【问题描述】:

我开玩笑的单元测试看起来像这样:

import React from 'react';
import renderer from 'react-test-renderer';
import ReactTestUtils from 'react-dom/test-utils'
import Calculator from "./calculator";

test('test that calculator', () => {
        const component = renderer.create(
            <Calculator></Calculator>
        );
        let tree = component.toJSON();
        expect(tree).toMatchSnapshot();
        console.log('component=',component.refs);

        // Simulate click on button -> trigger sumCalc()
        ReactTestUtils.Simulate.click(component.refs.button);

});

当我运行测试时,我得到:

TypeError: Cannot read property 'button' of undefined

我的反应组件如下所示:

import React, {Component} from 'react';

export default class Calculator extends Component {
    constructor(props) {
        super(props);
        this.calcSum = this.calcSum.bind(this);
        this.state = {sum: 0};
    }

    calcSum() {
        console.log('this.refs.one=', this.refs.one);
        let s = Number(this.refs.one.value) + Number(this.refs.two.value);
        this.setState({sum: s});
    }

    render() {
        return (<div>
                <input type="text" placeholder="number 1" ref="one"/>
                <input type="text" placeholder="number 2" ref="two"/>
                <button ref="button" onClick={this.calcSum}>sum</button>
                sum: {this.state.sum}
            </div>
        );
    }
}

如何避免此错误?我错过了什么? 该组件在渲染到 DOM 时可以工作,但单元测试存在问题。

【问题讨论】:

  • 请调试:console.log(tree.props.calcSum) 并发布日志...
  • 它返回:undefined
  • 应该是tree.calcSum();
  • 你没有通过任何props ^^

标签: unit-testing reactjs jestjs


【解决方案1】:

component.toJSON() 返回 JSON 而不是 JavaScript 对象。此外,calcSum 不是道具,而是在您的组件类上定义的方法。

因此您可以使用getInstance() 方法手动调用calcSum

试试这个:

  const component = renderer.create(<Calculator />);

  component.getInstance().calcSum();

现在您可以看到console.log 的输出来自calcSum

【讨论】:

    猜你喜欢
    • 2021-09-02
    • 1970-01-01
    • 2023-01-01
    • 2012-12-27
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 2015-07-10
    • 2020-09-11
    相关资源
    最近更新 更多