[英]Enzyme 3 get attributes of rendered DOM-node
我從myDomNode.html();
得到這個 html myDomNode.html();
<div aria-expanded="true"> {{someChildren}} </div>
在我的測試中,我想檢查aria-expanded
是否設置為 true。
使用酶 2.x 和反應 15.x,這是有效的: expect(myDomNode.attr('aria-expanded')).toBeTruthy();
但是在更新到 16.x 和酶 3.x 之后,我在更新后收到一個錯誤,該值未定義。 我在文檔中找不到任何有用的提示。
我得到這樣的myDomNode
:
const domNode = expanded => render(<Component expanded={expanded} />);
const myDomNode = domNode(true);
而渲染是從酶進口的。 我正在使用enzyme-adapter-react-16
Enzyme.configure({adapter: new Adapter()});
有趣的是myDomNode.is('div');
而myDomNode.is('[aria-expanded="true"]')
也是假的。
更新后如何修復測試?
僅供參考,這是失敗的測試之一: https : //github.com/mstruebing/PackageFactory.Guevara/blob/updateReact/packages/react-ui-components/src/ToggablePanel/toggablePanel.spec.js#L130
我克隆了你的 repo 並執行了測試。 我更改了一些功能,這就是我所做的:
const getHeaderDomNode = panelDomNode => panelDomNode['0'].children[0];
test('open ToggablePanel should render a <ToggablePanel.Header/> with an "aria-expanded" attribute of "true".', () => {
const wrapper = fullyRenderToggablePanel(true);
expect(getHeaderDomNode(wrapper).attribs['aria-expanded']).toBeTruthy();
});
重要的是,當我看到帶有console.log(wrapper)
的 'wrapper' 變量時,我發現了這個:
{
'0':
{
type: 'tag',
name: 'section',
namespace: 'http://www.w3.org/1999/xhtml',
attribs: { class: 'baseClassName isOpenClassName' },
'x-attribsNamespace': { class: undefined },
'x-attribsPrefix': { class: undefined },
children: [ [Object], [Object] ],
parent: null,
prev: null,
next: null,
root:
{
type: 'root',
name: 'root',
namespace: 'http://www.w3.org/1999/xhtml',
attribs: {},
'x-attribsNamespace': {},
'x-attribsPrefix': {},
children: [Array],
parent: null,
prev: null,
next: null
}
},
options:
{
withDomLvl1: true,
normalizeWhitespace: false,
xml: false,
decodeEntities: true
},
length: 1,
_root: [Circular]
}
所以,似乎如果你想訪問孩子你必須這樣做:
wrapper['0'].children
現在屬性在一個內部有文字對象的對象中,所以如果你想獲得一個屬性(例如:'arial-expanded'),你必須這樣做:
wrapper['0'].children[0]['arial-expanded']
您也可以使用屬性語法搜索元素並提取文本:
expect(wrapper.find('[aria-expanded]').prop('aria-expanded')).toBeTruthy();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.