@testing-library/react#getNodeText TypeScript Examples

The following examples show how to use @testing-library/react#getNodeText. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: detectChildrenChange.spec.tsx    From engine with MIT License 5 votes vote down vote up
test("should detect children change", async (done) => {
  const val = "321";
  const defaultState = {
    baz: "123",
  };
  const rootEl = document.createElement("div");
  rootEl.setAttribute("id", "root");
  document.body.appendChild(rootEl);
  const Child: view = ({ children }) => {
    // console.log(children);
    return <div>{children}</div>;
  };
  const Parent: view = ({ baz = observe.baz, trigger = update.trigger }) => {
    return (
      <div>
        <Child>
          <div data-testid="foo">{baz}</div>
        </Child>
        <div
          data-testid="change-baz"
          onClick={() => trigger.set(Math.random())}
        >
          trigger
        </div>
      </div>
    );
  };

  const changer: producer = ({
    trigger = observe.trigger,
    updateBaz = update.baz,
  }) => {
    if (!trigger) {
      return;
    }
    updateBaz.set("321");
  };

  const app = engine({
    state: defaultState,
    use: [render(<Parent />, rootEl), producers([changer])],
  });

  app.start();

  jest.runAllTimers();
  await flushPromises();
  waitFor(() => getByTestId(document.body, "foo")).then(async (x) => {
    const button = getByTestId(document.body, "change-baz");
    fireEvent.click(button);
    jest.runAllTimers();
    await flushPromises();
    const value = getNodeText(x);
    expect(value).toBe("321");
    done();
  });
});
Example #2
Source File: AutoComplete.test.tsx    From leda with MIT License 4 votes vote down vote up
describe('AutoComplete ATTRIBUTES', () => {
  describe('should render class', () => {
    test('className', () => {
      render((
        <AutoComplete
          className="test-class"
          onChange={jest.fn()}
          data={['value0', 'value1']}
        />
      ));
      expect(document.querySelectorAll('div.test-class')).toHaveLength(1);
    });
    test('danger', () => {
      render((
        <AutoComplete
          _danger
          onChange={jest.fn()}
          data={['value0', 'value1']}
        />
      ));
      expect(document.querySelectorAll('div.danger')).toHaveLength(1);
    });
    test('active', () => {
      render((
        <AutoComplete
          _active
          onChange={jest.fn()}
          data={['value0', 'value1']}
        />
      ));
      expect(document.querySelectorAll('div.active')).toHaveLength(1);
    });
  });
  describe('should render data', () => {
    test('string type', () => {
      const data = ['value0', 'value1'];
      render((
        <AutoComplete
          onChange={jest.fn()}
          data={data}
          isOpen
        />
      ));
      expect(screen.getAllByRole('listitem').map(getNodeText)).toEqual(data);
    });
    test('object type', () => {
      const data = [
        { id: 0, value: 'value0' },
        { id: 1, value: 'value1' },
      ];
      render((
        <AutoComplete
          onChange={jest.fn()}
          data={data}
          textField="value"
          isOpen
        />
      ));
      expect(screen.getAllByRole('listitem').map(getNodeText)).toEqual(data.map((value) => value.value));
    });
  });
  test('value adjustment to empty', () => {
    const onChangeHandler = jest.fn();
    const data = ['value0', 'value1'];
    const newValue = 'value';
    const eventMatcher = expect.objectContaining({
      target: expect.objectContaining({
        value: newValue,
      }),
      component: expect.objectContaining({
        method: 'type',
        value: newValue,
        suggestion: null,
      }),
    });
    render((
      <AutoComplete
        onChange={onChangeHandler}
        data={data}
        shouldCorrectValue
      />
    ));
    screen.getByRole('textbox').focus();
    userEvent.type(screen.getByRole('textbox'), newValue);
    expect(onChangeHandler).toBeCalledTimes(newValue.length);
    expect(onChangeHandler).lastCalledWith(eventMatcher);
    screen.getByRole('textbox').blur();
    expect(screen.getByRole('textbox')).toHaveValue('');
  });
  test('value adjustment to data value', () => {
    const onChangeHandler = jest.fn();
    const data = ['value0', 'value1'];
    const newValue = data[0];
    const eventMatcher = expect.objectContaining({
      target: expect.objectContaining({
        value: newValue,
      }),
      component: expect.objectContaining({
        method: 'type',
        value: newValue,
        suggestion: newValue,
      }),
    });
    render((
      <AutoComplete
        onChange={onChangeHandler}
        data={data}
        shouldCorrectValue
      />
    ));
    screen.getByRole('textbox').focus();
    userEvent.type(screen.getByRole('textbox'), newValue);
    expect(onChangeHandler).toBeCalledTimes(newValue.length);
    expect(onChangeHandler).lastCalledWith(eventMatcher);
    screen.getByRole('textbox').blur();
    expect(screen.getByRole('textbox')).toHaveValue(newValue);
  });
  test('data filtration', () => {
    const onChangeHandler = jest.fn();
    const value = 'value';
    const data = ['option', value, 'variant'];
    render((
      <AutoComplete
        onChange={onChangeHandler}
        data={data}
        isOpen
      />
    ));
    expect(screen.getAllByRole('listitem')).toHaveLength(3);
    userEvent.type(screen.getByRole('textbox'), 'va');
    expect(onChangeHandler).toBeCalledTimes(2);
    expect(screen.getAllByRole('listitem')).toHaveLength(2);
    userEvent.type(screen.getByRole('textbox'), 'val');
    expect(onChangeHandler).toBeCalledTimes(5);
    expect(screen.getAllByRole('listitem')).toHaveLength(1);
    expect(screen.getByRole('listitem')).toHaveTextContent(value);
  });
  test('compareObjectsBy', () => {
    const onChangeHandler = jest.fn();
    const newValue = 'value';
    const data = [
      { id: 0, name: 'value0' },
      { id: 1, name: 'value1' },
      { id: 2, name: newValue },
      { id: 3, name: newValue },
    ];
    render((
      <AutoComplete
        onChange={onChangeHandler}
        data={data}
        textField="name"
        compareObjectsBy="name"
      />
    ));
    screen.getByRole('textbox').focus();
    userEvent.type(screen.getByRole('textbox'), newValue);
    expect(onChangeHandler).toBeCalledTimes(newValue.length);
    expect(document.querySelectorAll('.selected')).toHaveLength(2);
  });
});
Example #3
Source File: DropDownSelect.test.tsx    From leda with MIT License 4 votes vote down vote up
describe('DropDownSelect SNAPSHOTS', () => {
  test('should render', () => {
    const data = [
      { id: 0, value: 'value0' },
      { id: 1, value: 'value1' },
    ];

    const wrapper = render((
      <DropDownSelect data={data} />
    ));

    expect(wrapper).toMatchSnapshot();
  });

  describe('controllable mode', () => {
    test('should render value', () => {
      const data = [
        { id: 0, value: 'value0' },
        { id: 1, value: 'value1' },
      ];

      const wrapper = render((
        <DropDownSelect textField="value" value={data[0]} data={data} />
      ));

      expect(screen.getByRole('textbox')).toHaveValue(data[0].value);
      expect(wrapper).toMatchSnapshot();

      wrapper.rerender((
        <DropDownSelect textField="value" value={data[1]} data={data} />
      ));

      expect(screen.getByRole('textbox')).toHaveValue(data[1].value);
      expect(wrapper).toMatchSnapshot();
    });

    test('should render data', () => {
      const data = [
        { id: 0, value: 'value0' },
        { id: 1, value: 'value1' },
      ];
      const wrapper = render((
        <DropDownSelect data={data.map((value) => value.value)} isOpen />
      ));

      screen.getByRole('textbox').focus();

      expect(screen.getAllByRole('listitem')).toHaveLength(data.length);
      expect(screen.getAllByRole('listitem').map(getNodeText)).toEqual(data.map((value) => value.value));
      expect(wrapper).toMatchSnapshot();

      screen.getByRole('textbox').blur();

      wrapper.rerender((
        <DropDownSelect data={data} textField="value" isOpen />
      ));

      screen.getByRole('textbox').focus();

      expect(screen.getAllByRole('listitem')).toHaveLength(data.length);
      expect(screen.getAllByRole('listitem').map(getNodeText)).toEqual(data.map((value) => value.value));
      expect(wrapper).toMatchSnapshot();
    });
  });

  describe('should test different component states', () => {
    test('should be isOpen', () => {
      const data = [
        { id: 0, value: 'value0' },
        { id: 1, value: 'value1' },
      ];

      const wrapper = render((
        <DropDownSelect textField="value" data={data} isOpen />
      ));

      expect(screen.getAllByRole('listitem')).toHaveLength(2);
      expect(wrapper).toMatchSnapshot();
    });

    test('should be disabled', () => {
      const wrapper = render((
        <DropDownSelect data={['0']} isDisabled />
      ));

      expect(screen.getByRole('textbox')).toBeDisabled();
      expect(wrapper).toMatchSnapshot();
    });
  });

  describe('multi-type attributes', () => {
    describe('data', () => {
      test('should render string data', () => {
        const data = ['value0', 'value1'];

        const wrapper = render((
          <DropDownSelect data={data} isOpen />
        ));

        expect(screen.getAllByRole('listitem')).toHaveLength(2);
        expect(wrapper).toMatchSnapshot();
      });

      test('should render object data', () => {
        const data = [
          { id: 0, value: 'value0' },
          { id: 1, value: 'value1' },
        ];

        const wrapper = render((
          <DropDownSelect data={data} textField="value" isOpen />
        ));

        expect(screen.getAllByRole('listitem')).toHaveLength(2);
        expect(wrapper).toMatchSnapshot();
      });
    });

    test('should render string placeholder', () => {
      const placeholder = 'placeholder';

      const wrapper = render((
        <DropDownSelect data={['0']} placeholder={placeholder} />
      ));

      expect(screen.getAllByPlaceholderText(placeholder)).toHaveLength(1);
      expect(wrapper).toMatchSnapshot();
    });
  });
});
Example #4
Source File: DropDownSelect.test.tsx    From leda with MIT License 4 votes vote down vote up
describe('DropDownSelect ATTRIBUTES', () => {
  test('should have className, change classes through props and className should not change prop-classes', () => {
    const wrapper = render((
      <DropDownSelect data={['0']} _box />
    ));

    expect(document.querySelector('div.dropdownselect-wrapper')).toHaveClass('box');

    wrapper.rerender((
      <DropDownSelect data={['0']} _active />
    ));

    expect(document.querySelector('div.dropdownselect-wrapper')).not.toHaveClass('box');
    expect(document.querySelector('div.dropdownselect-wrapper')).toHaveClass('active');

    wrapper.rerender((
      <DropDownSelect data={['0']} _active className="test" />
    ));

    expect(document.querySelector('div.dropdownselect-wrapper')).not.toHaveClass('box');
    expect(document.querySelector('div.dropdownselect-wrapper')).toHaveClass('active');
    expect(document.querySelector('div.dropdownselect-wrapper')).toHaveClass('test');
  });

  test('should display loader if dataLoading', () => {
    const wrapper = render((
      <DropDownSelect data={['0']} isOpen isLoading _box />
    ));

    expect(document.querySelectorAll('div.loader-wrapper')).toHaveLength(1);
    expect(document.querySelectorAll('span.loader-element')).toHaveLength(1);
    expect(wrapper).toMatchSnapshot();
  });

  test('should display noDataTemplate if no data', () => {
    const value = 'no data we are sorry';
    const noSuggestionsRender = () => (
      <span className="nodata">{value}</span>
    );
    const wrapper = render((
      <DropDownSelect isOpen noSuggestionsRender={noSuggestionsRender} _box />
    ));

    expect(document.querySelector('span.nodata')).toHaveTextContent(value);
    expect(wrapper).toMatchSnapshot();
  });

  test('should display custom values with string data', () => {
    const data = ['one', 'two'];
    const placeholder = 'placeholder';
    const transform = (value: string) => `--${value}--`;
    const itemRender = ({
      Element, elementProps,
    }: any) => (
      <Element {...elementProps}>{transform(elementProps.children)}</Element>
    );

    const wrapper = render(<DropDownSelect
      data={data}
      placeholder="placeholder"
      isOpen
      itemRender={itemRender}
      shouldAllowEmpty
    />);

    expect(screen.getAllByRole('listitem')).toHaveLength(1 + data.length);
    expect(screen.getAllByRole('listitem').map(getNodeText)).toEqual([placeholder, ...data].map(transform));
    expect(wrapper).toMatchSnapshot();
  });

  test('should render custom values with object data', () => {
    const data = [
      { id: 0, value: 'value0' },
      { id: 1, value: 'value1' },
    ];
    const transform = (value: string) => `--${value}--`;
    const itemRender = ({
      elementProps,
    }: any) => (
      <li {...elementProps}>{transform(elementProps.children)}</li>
    );

    const wrapper = render((
      <DropDownSelect
        data={data}
        placeholder="placeholder"
        textField="value"
        isOpen
        itemRender={itemRender}
      />
    ));

    expect(screen.getAllByRole('listitem').map(getNodeText)).toEqual(data.map((value) => transform(value.value)));
    expect(wrapper).toMatchSnapshot();
  });

  test('should display custom values with JSX', () => {
    const data = ['one', 'two'];
    const transform = (value: string) => `--${value}--`;
    const itemRender = ({
      elementProps,
    }: any) => (
      <li {...elementProps}>{transform(elementProps.children)}</li>
    );

    const wrapper = render(<DropDownSelect
      data={data}
      placeholder="placeholder"
      isOpen
      itemRender={itemRender}
    />);

    expect(screen.getAllByRole('listitem').map(getNodeText)).toEqual(data.map(transform));
    expect(wrapper).toMatchSnapshot();
  });

  describe('compareObjectsBy', () => {
    test('should set defaultValue as selected', () => {
      const data = [
        { id: 0, value: 'value0' },
        { id: 1, value: 'value1' },
      ];

      render(
        <DropDownSelect
          data={data}
          isOpen
          textField="value"
          defaultValue={{ ...data[0] }}
          compareObjectsBy="id"
        />,
      );

      expect(document.querySelector('li.selected')?.textContent).toEqual(data[0].value);
    });

    it('should not work if the string does not match data objects structure', () => {
      const data = [
        { id: 0, value: 'value0' },
        { id: 1, value: 'value1' },
      ];

      render(
        <DropDownSelect
          data={data}
          isOpen
          textField="value"
          defaultValue={{ ...data[0] }}
          compareObjectsBy="INVALID"
        />,
      );

      expect(document.querySelectorAll('li.selected')).toHaveLength(0);
    });

    it('should use function as value', () => {
      const data = [
        { id: 0, value: 'value0' },
        { id: 1, value: 'value1' },
      ];

      render(
        <DropDownSelect
          data={data}
          isOpen
          textField="value"
          defaultValue={{ ...data[0] }}
          compareObjectsBy={(item) => item.id}
        />,
      );

      expect(document.querySelector('li.selected')?.textContent).toEqual(data[0].value);
    });

    it('should not work if function return value does not match data objects structure', () => {
      const data = [
        { id: 0, value: 'value0' },
        { id: 1, value: 'value1' },
      ];

      render(
        <DropDownSelect
          data={data}
          isOpen
          textField="value"
          defaultValue={{ ...data[0] }}
          // @ts-ignore
          compareObjectsBy={(item) => item.INVALID}
        />,
      );

      expect(document.querySelectorAll('li.selected')).toHaveLength(0);
    });

    it('should set value as selected', () => {
      const data = [
        { id: 0, value: 'value0' },
        { id: 1, value: 'value1' },
      ];

      render(
        <DropDownSelect
          data={data}
          isOpen
          textField="value"
          value={{ ...data[0] }}
          compareObjectsBy={(item) => item.id}
        />,
      );

      expect(document.querySelector('li.selected')?.textContent).toEqual(data[0].value);
    });
  });
});