@testing-library/react#render TypeScript Examples

The following examples show how to use @testing-library/react#render. 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: escape.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Escape from active', () => {
  const ref = { current: null as unknown as DataSheetGridRef }
  render(<DataSheetGrid value={data} columns={columns} ref={ref} />)

  act(() => ref.current.setActiveCell({ col: 0, row: 0 }))

  userEvent.keyboard('[Escape]')
  expect(ref.current.activeCell).toEqual(null)
})
Example #2
Source File: all.test.tsx    From zustand-store-addons with MIT License 6 votes vote down vote up
it('uses the store with simplified fetch', async () => {
  const useStore = create(
    set => ({
      count: 1,
      inc: () => set(state => ({ count: state.count + 1 })),
    }),
    {
      computed: {
        doubleCount() {
          return this.count * 2;
        },
      },
    }
  );

  function Counter() {
    const [count, doubleCount, inc] = useStore('count, doubleCount, inc');
    React.useEffect(inc, []);
    return (
      <div>
        <p>count: {count}</p>
        <p>doubleCount: {doubleCount}</p>
      </div>
    );
  }

  const { findByText } = render(<Counter />);

  await findByText('count: 2');
  await findByText('doubleCount: 4');
});
Example #3
Source File: Wishlist.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('Wishlist', () => {

  it("renders list", async () => {
    const cstore = getCStore();
    cstore.addToWishlist({
      product: {
        id: 1,
        name: '_test3_'
      }
    });

    render(<AppPropsContext.Provider
      value={{
        pageProps: {
          cmsProps: {
            defaultPages: {
              product: 'product/[slug]',
            }
          }
        },
      }}><Wishlist /></AppPropsContext.Provider>);

    await screen.findByText('_test3_');
  });

})
Example #4
Source File: AddRows.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Calls addRows', () => {
  const addRows = jest.fn()
  render(<AddRows addRows={addRows} />)
  const button = screen.getByRole('button')
  const input = screen.getByRole('spinbutton')

  userEvent.click(button)
  expect(addRows).toHaveBeenLastCalledWith(1)

  userEvent.type(input, '{selectall}5')
  userEvent.click(button)
  expect(addRows).toHaveBeenLastCalledWith(5)

  userEvent.type(input, '{selectall}{backspace}{enter}')
  expect(addRows).toHaveBeenLastCalledWith(1)
})
Example #5
Source File: CurrencySwitch.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('CurrencySwitch', () => {

  it("renders currencies", async () => {
    const settings = getStoreItem('cmsSettings');
    setStoreItem('cmsSettings', {
      ...(settings ?? {}),
      currencies: [
        ...(settings?.currencies ?? []),
        {
          title: '_test1_',
          tag: '_test1_',
          id: '1',
        }
      ]
    });

    render(<CurrencySwitch />);

    await screen.findByText('_test1_');
  });
})
Example #6
Source File: AddRows.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Resets on blur when value is invalid', () => {
  render(<AddRows addRows={() => null} />)
  const input = screen.getByRole('spinbutton') as HTMLInputElement
  // Force the input to be of type "text" to test what happens if the user types in non-number characters
  input.type = 'text'

  act(() => {
    userEvent.type(input, '{selectall}{backspace}')
    input.blur()
  })
  expect(input.value).toBe('1')

  act(() => {
    userEvent.type(input, '{selectall}456xyz')
    input.blur()
  })
  expect(input.value).toBe('456')

  act(() => {
    userEvent.type(input, '{selectall}abc')
    input.blur()
  })
  expect(input.value).toBe('1')
})
Example #7
Source File: CategorySort.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('CategorySort', () => {

  it("renders default", async () => {
    render(<CategorySort />);

    await screen.findByText('Highest rated');
  });

  it("overrides options", async () => {
    render(<CategorySort
      overrideOptions={[
        {
          label: '_test1_',
          key: 'id',
        }
      ]}
    />);

    await screen.findByText('_test1_');
  });
})
Example #8
Source File: ContextMenu.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Closes properly', () => {
  const onClose = jest.fn()
  const { container } = render(
    <ContextMenu
      cursorIndex={{ col: 0, row: 0 }}
      clientX={0}
      clientY={0}
      items={[]}
      close={onClose}
    />
  )
  userEvent.click(container)
  expect(onClose).toHaveBeenCalled()
})
Example #9
Source File: checkout.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('/checkout', () => {

    it("renders cart", async () => {
        const cstore = getCStore();
        cstore.addToCart({
            product: testData
        })

        render(<CheckoutPage />);
        await screen.findByText(testData.name);
    });

    it("requests and renders order total", async () => {
        render(<CheckoutPage />);

        const cstore = getCStore();
        await screen.findByText(cstore.getPriceWithCurrency(10));
    });

})
Example #10
Source File: ContextMenu.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Click on item', () => {
  const onClose = jest.fn()
  const onInsertRowBelow = jest.fn()
  render(
    <ContextMenu
      cursorIndex={{ col: 0, row: 0 }}
      clientX={0}
      clientY={0}
      items={[{ type: 'INSERT_ROW_BELLOW', action: onInsertRowBelow }]}
      close={onClose}
    />
  )
  userEvent.click(screen.getByText('Insert row below'))
  expect(onInsertRowBelow).toHaveBeenCalled()
  expect(onClose).not.toHaveBeenCalled()
})
Example #11
Source File: index.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('/index', () => {

    it("renders posts", async () => {
        render(<Page
            posts={{
                pagedMeta: {
                    pageNumber: 1,
                    pageSize: 1,
                    totalElements: 1,
                },
                elements: [{
                    id: '_test_',
                    title: '_test_',
                }]
            }}
        />);

        await screen.findByText('_test_');
    });
})
Example #12
Source File: ContextMenu.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Check all items', () => {
  render(
    <ContextMenu
      cursorIndex={{ col: 0, row: 0 }}
      clientX={0}
      clientY={0}
      items={[
        { type: 'INSERT_ROW_BELLOW', action: () => null },
        { type: 'DELETE_ROW', action: () => null },
        { type: 'DUPLICATE_ROW', action: () => null },
        { type: 'DELETE_ROWS', fromRow: 1, toRow: 3, action: () => null },
        { type: 'DUPLICATE_ROWS', fromRow: 5, toRow: 7, action: () => null },
      ]}
      close={() => null}
    />
  )
  expect(screen.getByText('Insert row below')).toBeInTheDocument()
  expect(screen.getByText('Delete row')).toBeInTheDocument()
  expect(screen.getByText('Duplicate row')).toBeInTheDocument()
  expect(
    screen.getByText(textContentMatcher('Delete rows 1 to 3'))
  ).toBeInTheDocument()
  expect(
    screen.getByText(textContentMatcher('Duplicate rows 5 to 7'))
  ).toBeInTheDocument()
})
Example #13
Source File: SignIn.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('SignIn', () => {

    it("renders SignIn", async () => {
        render(<SignIn />);
        await screen.findByText('Login');
    });


    it("switches to forgot password", async () => {
        render(<SignIn />);
        await screen.findByText('Forgot your password?');

        screen.getByText('Forgot your password?').click();
        // "Reset password" button
        await screen.findByText('Reset password');
    });
})
Example #14
Source File: ContextMenu.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Fallback for unknown item', () => {
  render(
    <ContextMenu
      cursorIndex={{ col: 0, row: 0 }}
      clientX={0}
      clientY={0}
      items={[
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        { type: 'UNKNOWN_ITEM', action: () => null },
      ]}
      close={() => null}
    />
  )
  expect(screen.getByText('UNKNOWN_ITEM')).toBeInTheDocument()
})
Example #15
Source File: CImage.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('CImage', () => {

    it("renders children", async () => {
        render(<CImage id="1" image={{ alt: "_test1_" }} />);

        await screen.findByAltText('_test1_');
    });


})
Example #16
Source File: addRows.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Add single row', () => {
  const ref = { current: null as unknown as DataSheetGridRef }
  const onChange = jest.fn()

  render(
    <DataSheetGrid
      value={[
        { id: 1, firstName: 'Elon', lastName: 'Musk' },
        { id: 2, firstName: 'Jeff', lastName: 'Bezos' },
      ]}
      onChange={onChange}
      columns={columns}
      createRow={jest.fn().mockReturnValueOnce({ id: 3 })}
      ref={ref}
    />
  )

  userEvent.click(screen.getByText('Add'))

  expect(onChange).toHaveBeenCalledWith(
    [
      {
        id: 1,
        firstName: 'Elon',
        lastName: 'Musk',
      },
      {
        id: 2,
        firstName: 'Jeff',
        lastName: 'Bezos',
      },
      {
        id: 3,
      },
    ],
    [{ type: 'CREATE', fromRowIndex: 2, toRowIndex: 3 }]
  )
})
Example #17
Source File: CGallery.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('CGallery', () => {

    it("renders images", async () => {
        const result = render(<CGallery id="1" gallery={{
            loop: false,
            images,
        }} />);

        expect(result.container.querySelector(`[src=${images[0].src}]`)).toBeTruthy();
        expect(result.container.querySelector(`[src=${images[1].src}]`)).toBeTruthy();
    });

    it("renders slides", async () => {
        render(<CGallery id="1" gallery={{
            loop: false,
            slides: [
                <p key="1">_test3_</p>,
                <p key="2">_test4_</p>
            ]
        }} />);

        await screen.findByText('_test3_');
        await screen.findByText('_test4_');
    });


})
Example #18
Source File: arrows.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Up from cell', () => {
  const ref = { current: null as unknown as DataSheetGridRef }
  render(<DataSheetGrid value={data} columns={columns} ref={ref} />)

  act(() => ref.current.setActiveCell({ col: 1, row: 1 }))

  userEvent.keyboard('[ArrowUp]')
  expect(ref.current.activeCell).toEqual({
    col: 1,
    colId: 'firstName',
    row: 0,
  })
})
Example #19
Source File: AdminPanelWidgetPlace.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('AdminPanelWidget', () => {

    it("registers and renders all plugin widgets at place", async () => {
        registerWidget({
            widgetName: 'PluginSettings',
            pluginName: "_test1_",
            component: () => (<p>_test1_</p>)
        });

        render(<AdminPanelWidgetPlace
            widgetName="PluginSettings"
        />);

        await screen.findByText('_test1_');
    });

    it("registers and renders specific plugin widget at place", async () => {
        registerWidget({
            widgetName: 'PluginSettings',
            pluginName: "_test1_",
            component: () => (<p>_test1_</p>)
        });

        render(<AdminPanelWidgetPlace
            widgetName="PluginSettings"
            pluginName="_test1_"
        />);

        await screen.findByText('_test1_');
    });
})
Example #20
Source File: arrows.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Up from top row', () => {
  const ref = { current: null as unknown as DataSheetGridRef }
  render(<DataSheetGrid value={data} columns={columns} ref={ref} />)

  act(() => ref.current.setActiveCell({ col: 1, row: 0 }))

  userEvent.keyboard('[ArrowUp]')
  expect(ref.current.activeCell).toEqual({
    col: 1,
    colId: 'firstName',
    row: 0,
  })
})
Example #21
Source File: Welcome.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('Welcome page', () => {

    it("logs in, fetches user data", async () => {
        render(<WelcomePage />);

        const loginBtn = await screen.findByText('Create');

        const emailInput = document.getElementById('email-input');
        expect(emailInput).toBeTruthy();
        const passwordInput = document.getElementById('password-input');
        expect(passwordInput).toBeTruthy();
        const nameInput = document.getElementById('name-input');
        expect(nameInput).toBeTruthy();

        // fireEvent.change(nameInput, { target: { value: 'Michael' } });
        // fireEvent.change(emailInput, { target: { value: '[email protected]' } });
        // fireEvent.change(passwordInput, { target: { value: 'passs' } });
        // // fireEvent.click(loginBtn);

        // // await act(async () => {
        // //     const userInfo = getStoreItem('userInfo');
        // //     expect(userInfo.fullName).toEqual(testData.fullName);
        // // });
    });

})
Example #22
Source File: arrows.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Up from selection', () => {
  const ref = { current: null as unknown as DataSheetGridRef }
  render(<DataSheetGrid value={data} columns={columns} ref={ref} />)

  act(() =>
    ref.current.setSelection({
      min: {
        col: 1,
        row: 1,
      },
      max: {
        col: 2,
        row: 2,
      },
    })
  )

  userEvent.keyboard('[ArrowUp]')
  expect(ref.current.selection).toEqual({
    max: {
      col: 1,
      colId: 'firstName',
      row: 0,
    },
    min: {
      col: 1,
      colId: 'firstName',
      row: 0,
    },
  })
})
Example #23
Source File: ThemeMarket.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('PluginList page', () => {


    it("renders plugins", async () => {
        render(<Router><PluginMarket /></Router>);

        await screen.findByText('_test1_title');
        await screen.findByText('_test2_title');
    });

})
Example #24
Source File: arrows.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Cmd + Up', () => {
  const ref = { current: null as unknown as DataSheetGridRef }
  render(<DataSheetGrid value={data} columns={columns} ref={ref} />)

  act(() => ref.current.setActiveCell({ col: 1, row: 2 }))

  userEvent.keyboard('[MetaLeft>][ArrowUp][/MetaLeft]')
  expect(ref.current.activeCell).toEqual({
    col: 1,
    colId: 'firstName',
    row: 0,
  })
})
Example #25
Source File: Settings.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('Settings page', () => {

    it("renders settings", async () => {
        render(<SettingsPage />);

        const element = await screen.findByText('General');
        element.click();

        await screen.findByText((text) => text.includes(languages[0].name));
    });

})
Example #26
Source File: arrows.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Ctrl + Up', () => {
  const ref = { current: null as unknown as DataSheetGridRef }
  render(<DataSheetGrid value={data} columns={columns} ref={ref} />)

  act(() => ref.current.setActiveCell({ col: 1, row: 2 }))

  userEvent.keyboard('[ControlLeft>][ArrowUp][/ControlLeft]')
  expect(ref.current.activeCell).toEqual({
    col: 1,
    colId: 'firstName',
    row: 0,
  })
})
Example #27
Source File: PostList.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('PostList page', () => {

    it("renders posts", async () => {
        render(
            <Provider store={store}>
                <Router>
                    <PostListPage />
                </Router>
            </Provider>
        );

        await screen.findByText('_test1_');
        await screen.findByText('_test2_');
    });
})
Example #28
Source File: arrows.test.tsx    From react-datasheet-grid with MIT License 6 votes vote down vote up
test('Shift + Up', () => {
  const ref = { current: null as unknown as DataSheetGridRef }
  render(<DataSheetGrid value={data} columns={columns} ref={ref} />)

  act(() => ref.current.setActiveCell({ col: 1, row: 2 }))

  userEvent.keyboard('[ShiftLeft>][ArrowUp][/ShiftLeft]')
  expect(ref.current.selection).toEqual({
    min: {
      col: 1,
      colId: 'firstName',
      row: 1,
    },
    max: {
      col: 1,
      colId: 'firstName',
      row: 2,
    },
  })
})
Example #29
Source File: LoginPage.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('Login page', () => {

    it("logs in, fetches user data", async () => {
        render(<LoginPage />);

        const loginBtn = await screen.findByText('Login');

        const emailInput = document.getElementById('email-input');
        expect(emailInput).toBeTruthy();
        const passwordInput = document.getElementById('password-input');
        expect(passwordInput).toBeTruthy();

        fireEvent.change(emailInput, { target: { value: '[email protected]' } });
        fireEvent.change(passwordInput, { target: { value: 'passs' } });
        fireEvent.click(loginBtn);

        await act(async () => {
            const userInfo = getStoreItem('userInfo');
            expect(userInfo.fullName).toEqual(testData.fullName);
        });
    });
});