在测试使用 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');
});
})
最佳答案
如果我正确理解了这个问题,问题就在于如果
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');
我对这个解决方案不太满意,所以很高兴听到更好的解决方案,但它有效......
关于javascript - 测试 React-Bootstrap 组件时出现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41044226/