Home > Blockchain >  How to write unit test for render component
How to write unit test for render component

Time:02-15

Here is my render function

render() {
    const notes: any = [];
    this.props.value.forEach(element => {
      const note = {
        className: 'uitk-list-item',
        label: element.content,
        onClick: () => this.onMenuItemClick(element.content),
        typeAnchor: true,
        target: "_blank"
      };
      notes.push(note)
    });

    return (
        <><div>
          <UitkMenu
              id="show10"
              isOpen={this.state.show}
              onTriggerClick={this.handleClick}
          >
            <UitkMenuTrigger >
              <button style={buttonStyle}>
                <div className="notes">
                  {this.state.selectNote}
                </div>
                <div className="arrowState">
                  {arrowState}
                </div>
              </button>
            </UitkMenuTrigger>
            <UitkMenuContainer position={PositionType.LEFT} width={200}>
              <UitkMenuList items={notes} />
            </UitkMenuContainer>
          </UitkMenu>
        </div>
        </>
    )
  }
}

I want to create unit test for this part, I have a simple test now, but it doesn't work, the received length is 0 not 1, can anyone help with this? Also, are there any other tests I can have?

describe('selection component tests', () => {
    it('Renders correctly initial document', () => {
        const input = document.getElementsByClassName('notes');
        expect(input).toHaveLength(1)
    })
})

CodePudding user response:

You could just import your component and use render from testing library or shallow from enzyme. Both share differences. But this useCase will provide you with enough logic to test components, import them and render succesfully within jest env.

import {render} from '@testing-library/react';

it('renders', () => {
    render(
        <Drawer.Provider
          value={{isDrawerOpen: true}}
        >
          <ContactDrawers propForDrawer={'justinsertprops'} />
        </Drawer.Provider>
    );

    expect(ContactDrawers).toBeCalled();
  });
  • Related