【问题标题】:Issues Testing React-Bootstrap Components测试 React-Bootstrap 组件的问题
【发布时间】:2016-12-08 16:27:31
【问题描述】:

在测试将 React-Bootstrap 与 Mocha、Chai 和 Enzyme 结合使用的组件时,我遇到了一些困难。 希望有人能告诉我我做错了什么。

在测试不使用 React-Bootstrap 的组件时,我注意到输出是原始 html(),而在测试 React-Bootstrap 时,我只返回组件而不是原始 html()。这在尝试测试时引起了极大的头痛。如果我使用了 shallow、mount 和 render,就会发生这种情况。

如果有人知道为什么我在测试时无法获取原始 html,将不胜感激! 我已经包含了一些代码来显示我在说什么。

ReactTest.jsx

import React from 'react';

const ReactTest = () => (
  <div>
    <button>ReactTest</button>
  </div>
);

export default ReactTest;

ReactBootstrapTest.jsx

import React from 'react';
import { Button } from 'react-bootstrap';

const ReactBootstrapTest = () => (
  <div>
    <Button>ReactBootstrapTest</Button>
  </div>
);

export default ReactBootstrapTest;

reactTest.js

import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';

import ReactTest from '../../../../../../components/ReactTest';
import ReactBootstrapTest from '../../../../../../components/ReactBootstrapTest';

const reactTestEnzymeWrapper = () => (
  shallow(<ReactTest />)
);

const reactBootstrapTestEnzymeWrapper = () => (
  shallow(<ReactBootstrapTest />)
);

describe.only('ReactTest', () => {
  it('should output debug', () => {
    const reactTest = reactTestEnzymeWrapper();
    console.log('ReactTest', reactTest.debug());
  });

  it('should find the <button>', () => {
    const reactButton = reactTestEnzymeWrapper().find('button');
    expect(reactButton.at(0).text()).to.equal('ReactTest');
  });
});

describe.only('ReactBootstrapTest', () => {
  it('should output debug', () => {
    const reactBootstrapTest = reactBootstrapTestEnzymeWrapper();
    console.log('ReactBootstrapTest', reactBootstrapTest.debug());
  });

  it('should find the <button>', () => {
    const bootstrapButton = reactBootstrapTestEnzymeWrapper().find('button');
    expect(bootstrapButton.at(0).text()).to.equal('ReactBoostrapTest');
  });
})

【问题讨论】:

  • 你能发布测试的实际输出吗?

标签: javascript reactjs mocha.js react-bootstrap enzyme


【解决方案1】:

如果我正确理解了这个问题,那么问题是如果

item = shallow(<MyReactComponent>)

MyReactComponent 包含一个 React Bootstrap 项目,例如 id = itemId 然后

item.find('#itemId').text() 

返回类似

的东西
"<Button/>" 

而不是按钮中的实际文本。如果您按类或组件名称查找,同样适用。

我已经通过以下方式解决了这个问题:

item.find('#itemId').html()

然后使用辅助函数从 html 中解析出文本:

chai.expect(getBootstrapText(item.find('#butRemove').html())).to.equal('Remove Design');

我对这个解决方案不太满意,所以很高兴听到更好的解决方案,但它确实有效......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 2021-10-02
    相关资源
    最近更新 更多