lundi 27 janvier 2020

Test function in React functional component with Jest and Enzyme

I need to test a private function from a functional component, but I could not find a way to do it, someone can help? Thanks

This is my component code:

const PageHeader = props => {
  const { navLinks, toolTitle } = props;
  const { tool, toolGlobal } = toolTitle;
  const { authData, setAuthData } = useAuth();

  const [dropdownOpen, setDropdownOpen] = useState(false);
  const toggle = () => setDropdownOpen(prevState => !prevState);
  const logout = () => setAuthData('');

  return (
    <Header {...props}>
      <Container fluid>
        <Row className="align-items-center border-bottom pl-4">
          <Col sm="auto" className="d-flex">
            <h5 className="text-muted pr-2 mb-0 border-right">{toolGlobal}</h5>
            <h5 className="mb-0 pl-2 font-weight-bold">{tool}</h5>
          </Col>
          <Col className="d-flex align-items-center justify-content-center pl-0">
            <PageNav navLinks={navLinks} />
          </Col>
          <Col sm= className="d-flex align-items-center pl-0">
            <Dropdown isOpen={dropdownOpen} toggle={toggle}>
              <DropdownToggle tag="span" data-toggle="dropdown" aria-expanded={dropdownOpen}>
                <Button color="outline">
                  <i className="fas fa-user-circle text-black-50" />
                </Button>
              </DropdownToggle>
              <DropdownMenu right>
                <DropdownItem disabled>{authData.user_name}</DropdownItem>
                <DropdownItem divider />
                <DropdownItem onClick={logout}>Logout</DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </Col>
        </Row>
      </Container>
    </Header>
  );
};

I need to test the logout function

My test code:

describe('PageHeader', () => {
  useAuth.mockImplementation(() => context);

  const wrapper = shallow(<PageHeader />, { context });

  beforeEach(() => {
    wrapper.setProps({});
  });

... ...

  it('logout the user on DropDownItem Logout button', () => {
    // wrapper.setContext(context);
    /* Here I want to click the loguot button as 
       wrapper
         .find('Dropdown')
         .find('DropdownItem:last-child')
         .simulate('click');
       And then check the authData to findout if the
       logout function was called but nothing works */

    console.log(wrapper.context());
  });
});

I've got this error ShallowWrapper::context() can only be called on wrapped nodes that have a non-null instance

I've tried everything to test that function, nothing works as I hope, please help.

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire