所以我有一个特殊的问题,在我的react组件中,我使用了以下命令:
document.getElementById('modalsContainer').appendChild(recognitionProfileZoom); document.getElementById('modalsContainer').appendChild(categoryZoom);
和:
document.getElementById('cddoccategoryzoom').value;
但是由ID指定的这些元素在我的组件中不存在。 如何在测试中创建这些对象?
下面的代码将使用这些元素,但是会失败,因为它们不存在( hideModal函数使用document.append从before )
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 元素,实际上非常简单,您可以像在普通javascript中一样使用global关键字键入它:
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元素。