首页 文章

React:如何用jest模拟函数和测试组件渲染:

提问于
浏览
2

我很反应/开玩笑 . 我试图测试一个非常简单的反应组件,它从服务器获取数据并呈现响应 . 我的组件如下所示:

export default class myComponent extends Component {
    constructor(props) {
        super(props);
    }

     async componentDidMount() {
        try {
            let response = await axios.get(`server/url/endpoint`);
            this._processSuccess(response.data);
        } catch(e) {
            this._processFail(e);
        }
    }

    _processSuccess(response) {
        this.setState({pageTitle: response.data.title, text: response.data.text});
    }

    render() {
        return (
            <div className="title">{this.state.pageTitle}</div>
        );
    }
}

现在我想测试这个课程 . 我测试时:

  • 我想确保没有调用componentDidMount()

  • 我想将测试数据传递给_processSuccess

  • 最后检查渲染输出是否包含带有类 Headers 的div,其内部文本与我作为response.data / pageTitle提供的内部文本相同

我尝试过类似下面的内容:

import React from 'react'
import MyComponent from './MyComponent'
import renderer from 'react-test-renderer'
import { shallow, mount } from 'enzyme'

describe('MyComponent', () => {
    it('should display proper title', () => {
        const c = shallow(<MyComponent />);
        c._processSuccess(
            {data:{pageTitle:'siteName', test:'text'}}
        );
        // couldn't go further as Im getting error from the above line
    });
});

但是,我得到MyComponent._processSuccess不是函数错误 . 什么是正确的方法来做到这一点 .

1 回答

  • 3

    shallow() returns an Enzyme wrapper使用一些utils方法来测试渲染的组件 . 它确实 not 返回组件实例 . 这就是你在调用 c._processSucces() 时收到错误的原因 . 要访问该组件,您可以在包装器上使用.instance() method,因此以下内容应该有效:

    const c = shallow(<MyComponent />);
        c.instance()._processSuccess(
            {data:{pageTitle:'siteName', test:'text'}}
        );
    

    为了避免调用该组件的 componentDidMount() ,您可以在浅渲染器上尝试设置 disableLifecycleMethods ,但是我的文档不是100%明确的:

    const c = shallow(<MyComponent />, {
            disableLifecycleMethods: true
        });
    

    最后,您可以使用Enzyme的 contains()Jest assertion methods之一来检查输出是否包含预期的 <div>

    expect(c.contains(<div className="title" />)).toBe(true);
    

相关问题