@testing-library/react#cleanup TypeScript Examples

The following examples show how to use @testing-library/react#cleanup. 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: ListRaw.test.tsx    From ke with MIT License 6 votes vote down vote up
test('Use render function from `children`-props', () => {
  fc.assert(
    fc
      .property(
        listParamsArbitrary,
        listDataArbitrary,
        fc.boolean(),
        fc.lorem(),
        (params, data, isLoading, display) => {
          const renderSpy = jest.fn().mockReturnValue(display)
          const onParamsChangeSpy = jest.fn()

          const { getByText } = render(
            <ListView data={data} params={params} isLoading={isLoading} onParamsChange={onParamsChangeSpy}>
              <ListRaw>{renderSpy}</ListRaw>
            </ListView>
          )

          expect(renderSpy).toBeCalledTimes(1)
          expect(renderSpy).toHaveBeenCalledWith({
            data,
            status: { isLoading },
            params,
            onParamsChange: onParamsChangeSpy,
          })
          expect(getByText(display)).toBeInTheDocument()
        }
      )
      .afterEach(cleanup)
  )
})
Example #2
Source File: Input.test.tsx    From web3uikit with MIT License 6 votes vote down vote up
describe('Validation - Required', () => {
    beforeEach(() => {
        container = document.createElement('div');

        render(<Validation />, {
            container: document.body.appendChild(container),
        });
    });
    afterEach(() => {
        cleanup();
    });

    it('renders the required attribute', () => {
        const input: HTMLInputElement | null = container.querySelector(
            `[data-testid="${testInputId}"]`,
        );
        expect(input).toHaveAttribute('required');
    });

    it('validates a required input', async () => {
        const input: HTMLInputElement | null = container.querySelector(
            `[data-testid="${testInputId}"]`,
        );
        expect(input).not.toBeNull();

        input?.focus();
        input && fireEvent.change(input, { target: { value: '' } });
        input?.blur();

        expect(input?.checkValidity()).toBeFalsy;
    });
});
Example #3
Source File: ListOrderedData.test.tsx    From ke with MIT License 6 votes vote down vote up
test('Use component from `as`-props', () => {
  fc.assert(
    fc
      .property(
        listParamsArbitrary,
        listDataArbitrary,
        fc.boolean(),
        fc.lorem(),
        (params, data, isLoading, display) => {
          const orderDataSpy = jest.fn().mockReturnValue(display)

          const { getByText } = render(
            <ListView data={data} params={params} isLoading={isLoading} onParamsChange={jest.fn()}>
              <ListOrderedData as={orderDataSpy} />
            </ListView>
          )

          expect(orderDataSpy).toBeCalledTimes(1)
          expect(getByText(display)).toBeInTheDocument()
        }
      )
      .afterEach(cleanup)
  )
})
Example #4
Source File: App.test.tsx    From Notepad with MIT License 6 votes vote down vote up
describe("renders page with contents and basic features", () => {
  afterEach(cleanup);

  it("should have the 'TitleBar' component in 'App'", () => {
    render(<App />);
    const titleBarComponent = screen.getByTestId("title-bar");
    expect(titleBarComponent).toBeInTheDocument();
  });

  it("should have the 'MenuBar' component in 'App'", () => {
    render(<App />);
    const menuBarComponent = screen.getByTestId("menu-bar");
    expect(menuBarComponent).toBeInTheDocument();
  });

  it("should have the 'TextArea' component in 'App'", () => {
    render(<App />);
    const workAreaComponent = screen.getByTestId("work-area");
    expect(workAreaComponent).toBeInTheDocument();
  });

  it("should have the 'AlertBox' component in 'App'", () => {
    render(<App />);
    const alertBoxComponent = screen.getByTestId("alert-box-wrapper");
    expect(alertBoxComponent).toBeInTheDocument();
  });
});
Example #5
Source File: ListData.test.tsx    From ke with MIT License 6 votes vote down vote up
test('Use component from `as`-props', () => {
  fc.assert(
    fc
      .property(
        listParamsArbitrary,
        listDataArbitrary,
        fc.boolean(),
        fc.lorem(),
        (params, data, isLoading, display) => {
          const dataSpy = jest.fn().mockReturnValue(display)

          const { getByText } = render(
            <ListView data={data} params={params} isLoading={isLoading} onParamsChange={jest.fn()}>
              <ListData as={dataSpy} />
            </ListView>
          )

          expect(dataSpy).toBeCalledTimes(1)
          expect(getByText(display)).toBeInTheDocument()
        }
      )
      .afterEach(cleanup)
  )
})
Example #6
Source File: TitleBar.test.tsx    From Notepad with MIT License 6 votes vote down vote up
describe("renders home page with contents", () => {
  afterEach(cleanup);

  it("should have 'untitled.txt - notepad' title", () => {
    render(<TitleBar />);
    const titleElement = screen.getByText(/untitled.txt - notepad/i);
    expect(titleElement).toBeInTheDocument();
  });
});
Example #7
Source File: makeWrap.test.tsx    From ke with MIT License 6 votes vote down vote up
test('Props из нового компонента пробрасываются в оборачиваемый', () => {
  fc.assert(
    fc
      .property(fc.dictionary(fc.lorem(), fc.lorem()), (props) => {
        const wrapper = ({ children }: PropsWithChildren<{}>): JSX.Element => <div>{children}</div>
        const target = jest.fn().mockReturnValue(<div>TARGET</div>)

        const Wrapped = makeWrap(target, wrapper)
        // Тестируем на динамических пропсах
        /* eslint-disable react/jsx-props-no-spreading */
        render(<Wrapped {...props} />)

        expect(target).toHaveBeenCalledWith(props, {})
      })
      .afterEach(cleanup)
  )
})
Example #8
Source File: arrow.spec.tsx    From react-carousel with MIT License 6 votes vote down vote up
describe('<Arrow />', () => {
	afterEach(cleanup);

	it('should call onClick prop when click event occurs', async () => {
		const onClick = jest.fn();
		const { getByRole } = render(<Arrow direction="left" onClick={onClick} />);

		fireEvent.click(getByRole('button'));
		expect(onClick).toHaveBeenCalled();
	});
});
Example #9
Source File: makeWrap.test.tsx    From ke with MIT License 6 votes vote down vote up
test('При рендере созданного компонента используется результат обёртки', () => {
  fc.assert(
    fc
      .property(fc.string(), fc.lorem(), (targetResult, wrapperResult) => {
        const target = jest.fn().mockReturnValue(<div>{targetResult}</div>)
        const wrapper = jest.fn().mockReturnValue(<div>{wrapperResult}</div>)

        const Wrapped = makeWrap(target, wrapper)
        const { getByText } = render(<Wrapped />)

        expect(getByText(wrapperResult)).toBeInTheDocument()
      })
      .afterEach(cleanup)
  )
})
Example #10
Source File: navigation.spec.tsx    From react-carousel with MIT License 6 votes vote down vote up
describe('<Navigation />', () => {
	afterEach(cleanup);

	it('should render factory components in correct order', async () => {
		const onClick = jest.fn();
		const items = carouselItemNodes(5);
		const factory = (selected: boolean) => (
			<div>{selected ? 'selected' : 'unselected'}</div>
		);
		const { getByText, getAllByText } = render(
			<Navigation current={1} items={items} factory={factory} onClick={onClick} />,
		);

		expect(getByText('selected')).toBeTruthy();
		expect(getAllByText('unselected').length).toEqual(4);
	});

	it('should render call onClick callback for factory components', async () => {
		const onClick = jest.fn();
		const items = carouselItemNodes(5);
		const factory = (selected: boolean) => (
			<div>{selected ? 'selected' : 'unselected'}</div>
		);
		const { getByText } = render(
			<Navigation current={1} items={items} factory={factory} onClick={onClick} />,
		);

		fireEvent.mouseOver(getByText('selected'));
		expect(onClick).toHaveBeenCalled();
	});
});
Example #11
Source File: MultipleYears.test.tsx    From UsTaxes with GNU Affero General Public License v3.0 6 votes vote down vote up
withForm =
  (state: YearsTaxesState) =>
  async (
    f: (form: TestForm) => Promise<boolean | undefined>
  ): Promise<boolean> => {
    try {
      const form = new TestForm(state)

      try {
        const res = await f(form).catch((e) => {
          console.info('Error caught in handling promise.')
          console.info(e)
          console.info(form.rendered().container.innerHTML)
          form.cleanup()
          throw e
        })

        form.cleanup()
        return res ?? true
      } catch (e) {
        console.info('Error caught in handling outer.')
        console.info(e)
        console.info(form.rendered().container.innerHTML)
        form.cleanup()
        throw e
      }
    } catch (e) {
      console.error('Caught exception')
      console.info(state)
      throw e
    }
  }
Example #12
Source File: makeIntegrator.test.tsx    From ke with MIT License 6 votes vote down vote up
test('Рендер результата ведёт к рендеру корня', () => {
  fc.assert(
    fc
      .property(innersArbitrary, rootResultArbitrary, (inners, rootResult) => {
        const rootSpy = jest.fn().mockReturnValue(rootResult)
        const Integrator = makeIntegrator(rootSpy, inners)

        const { getByText } = render(<Integrator />)

        expect(getByText(rootResult)).toBeInTheDocument()
      })
      .afterEach(cleanup)
  )
})
Example #13
Source File: DownloadReportButton.test.tsx    From twilio-voice-notification-app with Apache License 2.0 6 votes vote down vote up
describe('DownloadReportButton', () => {
  beforeEach(async () => {
    fetch.mockResponse(
      JSON.stringify({
        recipients: [
          {
            callSid: 'C000001',
            to: '+1000002',
            status: CallStatus.COMPLETED,
          },
          {
            callSid: 'C000002',
            to: '+1000003',
            status: CallStatus.FAILED,
          },
        ],
      })
    );
  });

  afterEach(() => {
    cleanup();
    fetch.resetMocks();
  });

  test('renders correctly', async () => {
    await act(async () => {
      const { asFragment } = await render(<DownloadReportButton {...props} />);
      expect(asFragment()).toMatchSnapshot();
    });
  });
});
Example #14
Source File: ListView.test.tsx    From ke with MIT License 6 votes vote down vote up
test('Render children', () => {
  fc.assert(
    fc
      .property(
        listParamsArbitrary,
        listDataArbitrary,
        fc.boolean(),
        fc.lorem(),
        (params, data, isLoading, display) => {
          const { getByText } = render(
            <ListView data={data} params={params} isLoading={isLoading} onParamsChange={jest.fn()}>
              {display}
            </ListView>
          )

          expect(getByText(display)).toBeInTheDocument()
        }
      )
      .afterEach(cleanup)
  )
})
Example #15
Source File: BoardTile.test.tsx    From Twenty48 with GNU General Public License v3.0 6 votes vote down vote up
describe('Test Board Tile', () => {
  const testTile1 = getInitialTile()

  afterEach(() => {
    cleanup()
  })

  test('Render an initial tile', async () => {
    renderWithRecoil(<BoardTile tile={testTile1} />)

    const bTile = document.getElementById('board-tile')
    expect(bTile).toBeInTheDocument()
    expect(bTile?.firstChild?.textContent).toBe('')
    // tile has no value so ensure new animation is not set
    expect(!bTile?.classList.contains('new')).toBeTruthy()
  })
})
Example #16
Source File: Chat.test.tsx    From glific-frontend with GNU Affero General Public License v3.0 6 votes vote down vote up
describe('<Chat />', () => {
  afterEach(cleanup);

  test('it should render <Chat /> component correctly', async () => {
    render(
      <MemoryRouter>
        <MockedProvider mocks={mocks} addTypename={false}>
          <Chat />
        </MockedProvider>
      </MemoryRouter>
    );

    // there is nothing to assert here just waiting for all the mock calls working
    await waitFor(() => {});
    await waitFor(() => {});
  });
});
Example #17
Source File: index.unit.spec.tsx    From next-typescript-materialui-jest-starter with MIT License 6 votes vote down vote up
describe("Button Unit Tests", () => {
  afterEach(() => {
    sandbox.verifyAndRestore();
    cleanup();
  });

  it("should render", () => {
    // Arrange
    sandbox.spy(React, "createElement");

    // Act
    const { container } = render(
      <ThemeProvider theme={theme}>
        <Button color="primary" name={word()} />
      </ThemeProvider>
    );

    // Assert
    expect(container.querySelector("button")).toBeInTheDocument();
    expect((React.createElement as SinonStub).calledWith(MuiButton)).toBe(true);
  });
});
Example #18
Source File: InfiniteScroll.test.tsx    From chroma-react with MIT License 6 votes vote down vote up
beforeEach(() => {
  cleanup();

  jest.spyOn(infiniteScrollFunctions, 'getParentSize').mockReturnValue({
    bottom: 0,
  });

  jest.spyOn(infiniteScrollFunctions, 'getMySize').mockReturnValue({
    bottom: 0,
  });
});
Example #19
Source File: Popover.test.tsx    From design-system with MIT License 6 votes vote down vote up
describe('renders Popover component with prop: open and onToggle', () => {
  it('Popover component with open: false', () => {
    const { queryByTestId } = render(
      <Popover trigger={trigger} open={false} onToggle={FunctionValue}>
        Popover
      </Popover>
    );

    expect(queryByTestId('DesignSystem-Popover')).not.toBeInTheDocument();
  });

  it('Popover component with open and onToggle', () => {
    const open = true;
    const { getByTestId, queryByTestId, rerender } = render(
      <Popover trigger={trigger} open={open} onToggle={FunctionValue}>
        Popover
      </Popover>
    );

    expect(getByTestId('DesignSystem-Popover')).toBeInTheDocument();

    const popoverTrigger = getByTestId('DesignSystem-PopoverTrigger');
    fireEvent.click(popoverTrigger);
    expect(FunctionValue).toHaveBeenCalledWith(!open, 'onClick');

    rerender(
      <Popover trigger={trigger} open={!open} onToggle={FunctionValue}>
        Popover
      </Popover>
    );
    cleanup();
    expect(queryByTestId('DesignSystem-Popover')).not.toBeInTheDocument();
  });
});
Example #20
Source File: Tabs.test.tsx    From doc-blocks with MIT License 5 votes vote down vote up
afterEach(cleanup);
Example #21
Source File: player.test.tsx    From videojs-react-enhanced with MIT License 5 votes vote down vote up
describe(`Integrated Test - Wrapper Component`, () => {
  describe(`<Player />`, () => {
    let component: JSX.Element;
    it(`Renders and unmounts well without any error`, () => {
      // given
      component = <Player />;

      // when
      render(component);

      // done - no error occurs
      cleanup();
    });

    it(`Renders with options properly`, () => {
      // given
      const playerOptions: Player.IPlayerOptions = {
        controls: true,
        autoplay: 'play',
        src: 'https://sample.com/video.mp4',
      };
      const videojsOptions: Player.IVideoJsOptions = {
        fluid: true,
        language: 'ko',
        playbackRates: [0.5, 1.0, 1.5],
      };
      const hideList: Array<string> = [
        'playToggle'
      ];
      component =
        <Player
          playerOptions={playerOptions}
          videojsOptions={videojsOptions}
          hideList={hideList}
          onPlay={() => { }}
          onReady={() => { }}
        />

      // when
      render(component);

      // done - no error occurs
      cleanup();
    });

    it(`Renders well with plugins`, () => {
      // given
      videojs.registerPlugin('PluginB', (options: any) => {})

      const plugins: Array<Player.IVideoJsPlugin> = [
        {
          name: 'PluginA',
          plugin: (option) => { },
          options: { settings: true },
        },
        {
          name: 'PluginB',
          options: { settings: false },
        },
      ];
      const videojsOptions: Player.IVideoJsOptions = {
        plugins,
      }

      component =
      <Player
        videojsOptions={videojsOptions}
      />

      // when
      render(component);

      // done - no error occurs
      cleanup();
      videojs.deregisterPlugin('PluginA');
      videojs.deregisterPlugin('PluginB');
    });
  });
});
Example #22
Source File: App.test.tsx    From Twenty48 with GNU General Public License v3.0 5 votes vote down vote up
describe('Initial render App', () => {

  afterEach(() => {
    cleanup()
  })

  test('render app with default dark theme', async () => {
    renderWithRecoil(<App />)
    const twenty = screen.getByText("Twenty");
    const forty = screen.getByText("Forty");
    const eight = screen.getByText("Eight");

    expect(twenty).toBeInTheDocument();
    expect(forty).toBeInTheDocument();
    expect(eight).toBeInTheDocument();
    // dark theme by default
    expect(twenty.parentElement).toHaveClass('gameboard-header-c1-dark')
  })

  test('render app and open popover', async () => {
    renderWithRecoil(<App />)
    const settingsCog = document.getElementById('settings-cog')
    const score = screen.getByText("Score");
    const newGame = screen.getByText("New Game");
    const bestScore = screen.getByText("Best Score");
    const clearBtn = screen.getByText("Clear");

    expect(score).toBeInTheDocument();
    expect(newGame).toBeInTheDocument();
    expect(bestScore).toBeInTheDocument();
    expect(clearBtn).toBeInTheDocument();
    if (settingsCog) {
      fireEvent.click(settingsCog)
    }
    const popover = document.getElementsByClassName('popover-body')[0]
    expect(popover).toBeInTheDocument();

    const theme = screen.getByText('dark')
    const cache = screen.getByText('Clear')
    expect(theme).toBeInTheDocument();
    expect(cache).toBeInTheDocument();
  })

});
Example #23
Source File: checkbox_tl.test.tsx    From skin-react with MIT License 5 votes vote down vote up
afterEach(cleanup);
Example #24
Source File: DropdownSelect.spec.tsx    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
afterEach(cleanup);
Example #25
Source File: ChatConversations.test.tsx    From glific-frontend with GNU Affero General Public License v3.0 5 votes vote down vote up
afterEach(cleanup);
Example #26
Source File: NewFileWizard.test.tsx    From pybricks-code with MIT License 5 votes vote down vote up
afterEach(() => {
    cleanup();
});
Example #27
Source File: Button.test.tsx    From frontend with GNU General Public License v3.0 5 votes vote down vote up
afterEach(cleanup);
Example #28
Source File: Input.test.tsx    From web3uikit with MIT License 5 votes vote down vote up
describe('Validation - Number Range', () => {
    beforeEach(() => {
        container = document.createElement('div');

        render(<ValidateNumberRange />, {
            container: document.body.appendChild(container),
        });
    });
    afterEach(() => {
        cleanup();
    });

    it('renders HTML validation attributes', () => {
        const input: HTMLInputElement | null = container.querySelector(
            `[data-testid="${testInputId}"]`,
        );
        expect(input).toHaveAttribute('min');
        expect(input).toHaveAttribute('max');
    });

    it('validates a the valid input', async () => {
        const goodValue =
            Number(ValidateNumberRange?.args?.validation?.numberMax) - 1;
        const input: HTMLInputElement | null = container.querySelector(
            `[data-testid="${testInputId}"]`,
        );
        expect(input).not.toBeNull();

        input?.focus();
        input && fireEvent.change(input, { target: { value: `${goodValue}` } });
        input?.blur();

        expect(input?.checkValidity()).toBeTruthy;
    });

    it('validates a the non valid input', async () => {
        const badValue =
            Number(ValidateNumberRange?.args?.validation?.numberMax) + 1;
        const input: HTMLInputElement | null = container.querySelector(
            `[data-testid="${testInputId}"]`,
        );
        expect(input).not.toBeNull();

        input?.focus();
        input && fireEvent.change(input, { target: { value: `${badValue}` } });
        input?.blur();

        expect(input?.checkValidity()).toBeFalsy;
    });
});
Example #29
Source File: MultipleYears.test.tsx    From UsTaxes with GNU Affero General Public License v3.0 5 votes vote down vote up
// RTL's cleanup method only after each
// jest test is done. (Not each property test)
afterEach(() => {
  cleanup()
})