使用React / Mocha / Chai进行UI测试 - 如何测试元素的宽度

时间:2016-05-05 00:27:46

标签: javascript reactjs chai

我正在学习如何在做出反应的UI组件上进行一些测试。我遇到了一个问题 - 我有一个场景,首先,<input>字段的宽度为0px。用户单击一个按钮,宽度动画为200px。用户再次单击一个按钮,<input>再次收缩为0px。

我遇到的问题(使用Chai Jquery)是在选择组件的.width()时,它总是返回0px。一些谷歌搜索表明这种情况发生在Jquery中,因为DOM还没有加载。有没有办法在测试中调用componentDidMount(),并在之后进行断言?

编辑这是我用来渲染组件的功能(来自教程):

function renderComponent(ComponentClass, props = {}, state = {}) {
  const componentInstance =  TestUtils.renderIntoDocument(
    <Provider store={createStore(reducers, state)}>
      <ComponentClass {...props} />
    </Provider>
  );

  return $(ReactDOM.findDOMNode(componentInstance));
}

通过将React组件传递到ComponentClass字段来调用它。我正在使用的示例测试:

  // other imports
  import Navbar from '../../src/containers/navbar';

  let component;

  beforeEach(() => {
    component = renderComponent(Navbar);
  });

  it('has the class nav-bar', () => {
    expect(component).to.have.class('nav-bar');
  });

我试图运行的那种测试:

it('has an initial width of 0px', () => {
  // this is always true
  expect(component.find('input').width()).to.equal(0);
});

0 个答案:

没有答案