代码之家  ›  专栏  ›  技术社区  ›  bigpotato

React+Jest:如何测试私有样式的组件?

  •  0
  • bigpotato  · 技术社区  · 6 年前

    我有一个 Charities status === "error" :

    import React from "react";
    import styled from "styled-components";
    
    const Notification = styled.p`
      text-align: center;
      padding: 10px;
      font-family: Raleway;
      display: ${props => (props.hide ? "none" : "block")};
    `;
    
    const ErrorNotification = styled(Notification)`
      background: #e3c7c4;
    `;
    
    export const Charities = ({
      ..., status
    }) => (
      <Container>
        <ErrorNotification hide={status !== "error"}>
          Sorry, something was wrong with your payment. Please try again.
        </ErrorNotification>
        ...
      </Container>
    );
    
    export default Charities;
    

    我试着用这样的笑话来测试这个:

    import React from "react";
    import { mount, shallow } from "enzyme";
    import { Charities } from "./index";
    
    describe("Charities", () => {
      let props;
      let mountedCharities;
      const charities = () => {
        if (!mountedCharities) {
          mountedCharities = mount(<Charities {...props} />);
        }
        return mountedCharities;
      };
    
      beforeEach(() => {
        props = {
          status: undefined,
          ...
        };
        mountedCharities = undefined;
      });
    
      describe("when status is pending", () => {
        beforeEach(() => {
          props.status = "pending";
        });
    
        it("doesn't render error", () => {
          expect(charities().text()).not.toMatch(/Sorry/); // <---------- FAILS
        });
      });
    });
    

    Expected value not to match:
      /Sorry/
    Received:
      "Sorry, something was wrong with your payment. Please try again.Congratulations! You have successfully made a donation."
    

    它似乎正在加载样式化组件的子组件,即使它不满足条件。我怎么测试这个?

    2 回复  |  直到 6 年前
        1
  •  0
  •   Brian Adams    6 年前

    你的代码按预期工作,只是 styled() 通过在元素上放置类名来控制样式。

    单元测试中 ErrorNotification 仍然存在,但是上面有css类 display: none

    为了使组件更易于单元测试,我建议在 Charities 这样地:

    import React from "react";
    import styled from "styled-components";
    
    const Notification = styled.p`
      text-align: center;
      padding: 10px;
      font-family: Raleway;
      display: block;
    `;
    
    const ErrorNotification = styled(Notification)`
      background: #e3c7c4;
    `;
    
    export const Charities = ({
      ..., status
    }) => (
      <Container>
        {status !== "error" ? null : (
          <ErrorNotification>
            Sorry, something was wrong with your payment. Please try again.
          </ErrorNotification>
        )}
        ...
      </Container>
    );
    
    export default Charities;
    

    慈善机构 除了 'error' 错误通知 不会被渲染。

        2
  •  0
  •   Code Ranger    6 年前

    { status === "error" && 
      <ErrorNotification >
         Sorry, something was wrong with your payment. Please try again.
      </ErrorNotification>
    }