【问题标题】:How to test for the string '...loading' in React component that uses styled-components?如何在使用样式组件的 React 组件中测试字符串“...正在加载”?
【发布时间】:2020-02-27 23:22:18
【问题描述】:

如何为样式化组件编写开玩笑酶断言?

通常我会这样设置测试:

import React from 'react';
import { shallow } from 'enzyme';
// test-setup.js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Post from '../components/Post';
import Header from '../components/Header';
import HeaderDefaultPropsInit from './default-props/Header.defaultProps';
//import localStorage from './../../setUpTests';

configure({ adapter: new Adapter() });

describe('The header before all of the articles have been read', () => {
  let wrapper;
  beforeEach(() => {
    const defaultProps = {
      ...HeaderDefaultPropsInit,
      fetchPost: jest.fn(),
      history: {
        push: jest.fn(),
      },

    };
    wrapper = shallow(<Header  {...defaultProps} />);
  });

wrapper 的输出看起来几乎就像一个普通的 html 块。 通常我使用wrapper.find('some-element') 像这样写断言:

it('renders the image correctly', () => {
     expect(wrapper.find('.image').hasClass('image')).toBe(true);
   });

但这是为了测试由酶渲染的jsx的输出,并且输出很容易遍历,因为你可以使用jQuery类型语法,因为它就像html一样。

但是:

当我使用样式化组件时,结果 console.log(wrapper.debug()) 这是:

  <styled.div>
        <styled.div color={[undefined]}>
          <styled.span>
            ...loading
          </styled.span>
          <br />
          <strong className="h4">
            <styled.span />
          </strong>
        </styled.div>
      </styled.div>

没有正常的 html 元素可以编写正常的断言!

你到底是怎么写断言的:

<styled.div>

而不是

<div class="some-class">

没有什么可以将一个元素与另一个元素区分开来

expect(wrapper.find('styled.div').contains('..loading')).toBe(true);

可以引用任何 styled.div

我只想测试它是否包含“..loading”消息。 我一定遗漏了一些明显的东西——其他人是怎么做到的?

【问题讨论】:

    标签: reactjs jestjs enzyme styled-components


    【解决方案1】:

    答案是在创建样式组件后为其指定一个显示名称。

    const CalloutWrapper = styled.div`
      width: 450px;
    `;
    
    
    CalloutWrapper.displayName = 'CalloutWrapper';
    

    然后当你用console.log(wrapper.debug())渲染它时

    看起来像这样:

     <CalloutWrapper>
       ...loading
     </CalloutWrapper>
    

    你几乎可以像平常一样做断言

     it('it renders  the loading message', () => {
        expect(wrapper.find('CalloutWrapper').html()).toContain('...loading');
      });
    

    看这里https://github.com/styled-components/styled-components/issues/896

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-15
      • 2017-04-09
      • 2021-11-25
      • 2020-08-08
      • 2019-01-17
      • 2020-09-29
      • 1970-01-01
      • 2019-01-14
      相关资源
      最近更新 更多