簡體   English   中英

如何在使用React DOM的單元測試中觸發狀態更改?

[英]How can I trigger a state change in a unit test with React DOM?

我正在使用React Test Utilities對我的一些代碼進行單元測試。 我調用renderIntoDocument渲染自定義組件,然后使用findDOMNode測試渲染的內容。 我遇到的麻煩是,我不確定如何在單元測試的上下文中更新狀態並有效觸發重新渲染。

這是一些示例代碼-請注意代碼注釋:

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-dom/test-utils';
import MyCustomComponent from '../../app/components/MyCustomComponent';

describe('My Test Suite', () => {
    let component, node;
    test('verify state change', () => {
        const items = [{'value': '1'}];
        component = TestUtils.renderIntoDocument(
            <MyCustomComponent items={items} />
        );
        node = ReactDOM.findDOMNode(component);
        expect(node.querySelector('input[type=text]').value).toEqual('1');
        component.state.items = [{'value': '2'}];
        // do something here to trigger a re-render?
        expect(node.querySelector('input[type=text]').value).toEqual('2');
    });
});

不幸的是,改變狀態變量似乎無濟於事。 而且我無法調用component.componentWillReceiveProps()因為這似乎沒有定義。

請注意 ,我確實希望同一個組件調用其渲染函數,而不是用一個全新的組件有效地替換它。 原因是因為我發現了一個錯誤,該錯誤導致組件基於this.props而不是this.state渲染事物,並且我想進行測試以表明它始終使用狀態中的數據,而不是初始值。

AirBnb的對此具有一些強大的實用程序。 您需要安裝依賴項,但是它很簡單,可以對其進行配置。 然后,您可以簡單地在組件實例上調用Enzyme的setState方法 重要說明–在這種情況下,您的“組件實例”是淺淺呈現的組件 您的代碼如下所示:

import React from 'react';
import MyCustomComponent from '../../app/components/MyCustomComponent';
import { shallow, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

// configure your adapter
configure({ adapter: new Adapter() });

describe('My Test Suite', () => {

    test('verify state change', () => {
        const items = [{'value': '1'}];
        const wrapper = shallow(<MyCustomComponent items={items} />);

        // find your shallow rendered component and check its value
        expect(wrapper.find('input[type="text"]').value).toEqual('1');

        // set the state of the component
        wrapper.setState({ items: [{'value': '2'}] });

        // state should be updated, make sure its value was properly set
        expect(wrapper.find('input[type="text"]').value).toEqual('2');
    });
});

所有這些都假定您在組件中正確使用了state 在您的情況下, items似乎是作為prop傳遞的。 如果您只是通過復制props來設置state ,則可能需要重新考慮您的策略。 無論如何,這種方法應該與React中state更新的工作方式相同–您在同一組件實例上進行操作而無需卸載和重新安裝組件。 希望這可以幫助。

暫無
暫無

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

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