【问题标题】:Unable to find an element on DOM having two classes using expect test library with enzyme使用带有酶的期望测试库无法在具有两个类的 DOM 上找到元素
【发布时间】:2020-03-01 16:40:43
【问题描述】:

在测试 React-Redux 组件时,有没有办法通过第二个类名或具有两个或多个类名的元素来查找元素?

例如,我有一个 div:

<div className="navigations active">
....
</div>

虽然我可以通过第一类名称找到它

const wrapper = mount(
   <Provider store={store}>
       <TodoApp />
   </Provider>
);

expect(wrapper.find('.navigations ')).toHaveLength(4);

但无法通过第二类名称找到它。例如:

expect(wrapper.find('.active')).toHaveLength(1);

它总是给我零长度,但活动类附加到 DOM。 我只是想知道有没有办法访问它。

【问题讨论】:

    标签: reactjs react-redux jestjs enzyme


    【解决方案1】:

    您应该能够同时做到这两个...我创建了快速测试来检查您的示例:

    import React from 'react';
    import { mount } from 'enzyme';
    
    const MyComp = ({active}) => <div className={`navigations${active ? ' active': ''}`} />;
    
    describe('Name of the group', () => {
      it('should ', () => {
        const wrapper = mount(
          <>
            <MyComp />
            <MyComp active/>
            <MyComp />
            <MyComp />
          </>,
        );
    
        expect(wrapper.find('.navigations')).toHaveLength(4);
        expect(wrapper.find('.active')).toHaveLength(1);
      });
    });
    

    【讨论】:

    • 用 redux 来做
    • 将你的代码分享给一些沙箱,比如codebin等。这样会更容易
    • 告诉我你的 github 用户名,以便我可以访问你
    • 我的github是MaciejTrojniarz
    猜你喜欢
    • 2022-12-03
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 2014-01-12
    相关资源
    最近更新 更多