所以我有一个特殊的问题,在我的反应组件中我使用了这样的命令:
document.getElementById('modalsContainer').appendChild(recognitionProfileZoom);
document.getElementById('modalsContainer').appendChild(categoryZoom);
和:
document.getElementById('cddoccategoryzoom').value;
但是我的组件中不存在由ID指定的这些元素。 如何在测试中创建这些对象?
下面的代码将使用这些元素,但它失败,因为它们不存在(hideModal函数利用之前的document.append)
describe("CaptureProfileModal functions tests", function() {
it('Should hide the modal', function() {
var wrapper, instance;
wrapper = mount(
<CaptureProfileModal
gridAction={1}
captureSettingCode={15}
fields={mockedFields}/>
);
wrapper.setState({
showModal: true
});
instance = wrapper.component.getInstance();
instance.hideModal();
});
在酶测试中创建DOM元素:
所以大家,要在你的测试中创建DOM元素,它实际上非常简单,你可以像在vanilla javascript中一样输入它,使用全局关键字:
it('Should hide the modal', function() {
var wrapper, instance;
var modalsContainer = global.document.createElement('div');
var recognitionProfileZoom = global.document.createElement('div');
var categoryZoom = global.document.createElement('div');
modalsContainer.id = 'modalsContainer';
recognitionProfileZoom.id = 'recognitionProfileZoom';
categoryZoom.id = 'categoryZoom';
global.document.body.appendChild(modalsContainer);
global.document.body.appendChild(recognitionProfileZoom);
global.document.body.appendChild(categoryZoom);
完成此操作后,您可以预期值,并正常使用DOM元素。