0

我无法为按钮属性编写正确的测试用例disable。我使用TestUtils来自react-addons-test-utils.

我有非常简单的组件:

const propTypes = {
    disabled: PropTypes.func.isRequired
};

class MyComponent extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <span>
                <button id="my-button" type="submit" disabled={this.props.disabled}>
                    MyButton
                </button>
            </span>
        );
    }
}

MyComponent.propTypes = propTypes;

export default MyComponent;

我想编写测试来检查按钮是否被给定的道具禁用或未被禁用。测试如下所示:

describe('MyComponent', () => {
    it('should render disabled button when props.disabled is equal to true', () => {
        // given
        const props = {
            disabled: () => true
        };

        // when
        const myComponent = TestUtils.renderIntoDocument(<MyComponent {...props}/>);

        // then
        const root = ReactDOM.findDOMNode(myComponent);
        const myButton = root.querySelector('#my-button');
        expect(myButton.disabled).toEqual(true);
    });

    it('should render enebled button when props.disabled returns false', () => {
        // given
        const props = {
            disabled: () => false
        };

        // when
        const myComponent = TestUtils.renderIntoDocument(<MyComponent {...props}/>);

        // then
        const root = ReactDOM.findDOMNode(myComponent);
        const myButton = root.querySelector('#my-button');
        expect(myButton.disabled).toEqual(false);
    })
});

而且这种测试的实现不起作用。第一次测试通过但第二次失败。

但是当 propTypes 设置为disabled: false而不是disabled: () => false两个测试都成功时。

问题是为什么测试是成功的,当函数disabled是一个等于 false 的布尔常量值并且当disabled一个函数返回时不起作用false

失败测试日志:

期望(收到).toEqual(期望)

Expected value to equal:
  false
Received:
  true

  at Object.<anonymous> (__tests__/unit/components/create/MyComponent-test.js:90:37)
      at new Promise (<anonymous>)
      at <anonymous>
  at process._tickCallback (internal/process/next_tick.js:118:7)
4

1 回答 1

1

看起来您正在将函数分配给属性值,而不是函数的返回值,您可以通过使用来调用,

const props = {
   disabled: function() {
      return false;
    }()
}

否则,您需要disabled在测试时调用您的函数,

expect( myButton.disabled() ).toEqual(false);
于 2018-03-23T16:18:18.123 回答