簡體   English   中英

反應:如何通過嘲笑來模擬函數並測試組件渲染:

[英]React: How mock functions and test component rendering with jest:

我很新來的反應/開玩笑。 我試圖測試一個非常簡單的react組件,該組件從服務器獲取數據並呈現響應。 我的組件如下所示:

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>
        );
    }
}

現在,我想測試這個課程。 當我測試時:

  1. 我想確保未調用componentDidMount()
  2. 我想將測試數據傳遞給_processSuccess
  3. 最后檢查渲染的輸出是否包含具有類標題的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不是函數錯誤。 這樣做的正確方法是什么?

shallow() 返回一個帶有一些utils方法的酶包裝器 ,以測試渲染的組件。 不會返回組件實例。 這就是為什么在調用c._processSucces()時收到錯誤的原因。 要訪問該組件,可以在包裝器上使用.instance()方法 ,因此以下各項應適用:

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

為了避免調用該組件的componentDidMount() ,可以嘗試在淺層渲染器上設置disableLifecycleMethods ,但是我不確定,因為此處酶的文檔不是100%清晰的:

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

最后,您可以使用Enzyme的contains()Jest斷言方法之一來檢查輸出是否包含預期的<div>

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM