Ошибка при запуске шут-теста с библиотекой реагирования-тестирования - PullRequest
0 голосов
/ 14 февраля 2019

Я впервые пишу тесты.Я пишу тесты для приложения ReactJS, написанного с помощью ловушек, и тестирую с использованием Jest и реагирующая библиотека-тестирования .

Вот мой функциональный компонент:

const ItemDetails = ({ item }) => {
  const { code } = item;
  const { getBarcode } = useStationContext();

  return (
    <>
      <Button
        type="primary"
        onClick={() => {
          getBarcode(code);
        }}
        style={{ float: 'right' }}
      >
        Print Barcode
      </Button>
      <List
        bordered
        dataSource={formatData(item)}
        renderItem={({ title, value }) => (
          <List.Item>
            <List.Item.Meta
              description={
                <Wrapper>
                  <p>{upperCase(title)}</p>
                  <div>{value}</div>
                </Wrapper>
              }
            />
          </List.Item>
        )}
      />
    </>
  );
};

export default ItemDetails;

и тестовый файл:

import React from 'react';
import { render, cleanup } from 'react-testing-library';
import ItemDetails from '../containers/Items/ItemPage/ItemDetails';

afterEach(cleanup);

describe('formatData()', () => {
  it('Return Details about item', async () => {
    const { getByText, getByTestId, container, asFragment } = render(
      <ItemDetails
        item={{
          id: '296-c-4f-89-18',
          barcode: 'E-6',
        }}
      />,
    );

    global.console = {
      log: jest.fn(getByText, getByTestId, container, asFragment),
    };

    expect(global.console.log).toHaveBeenCalledWith('test');
  });
});

Когда я запускаю тест, я получаю эту ошибку:

TypeError: Невозможно прочитать свойство 'getBarcode' из null

Не знаю, как это исправить?

1 Ответ

0 голосов
/ 14 февраля 2019

Ожидания неверны, потому что console.log никуда не вызывается.Пересмешивание console объекта типа global.console = ... является плохой практикой, поскольку оно сохраняется между тестами и может нарушать все, что от него зависит, включая самого бегуна.

Имеется несоответствие с ключом элемента code.as barcode.

Ожидается, что значение контекста будет undefined, если не указано значение по умолчанию.Это должно быть указано в тесте.

Вероятно, должно быть:

const getBarcodeMock = jest.fn();

const { getByText, getByTestId, container, asFragment } = render(
 <StationContext.Provider value={{ getBarcode: getBarcodeMock }}>
  <ItemDetails
    item={{
      id: '296-c-4f-89-18',
      code: 'E-6',
    }}
  />
 </StationContext.Provider>
);

// ...simulate button click...

expect(getBarcodeMock).toBeCalledWith('E-6');
...