使用React-Testing-Library运行Jest测试时出错

时间:2019-02-14 11:35:05

标签: reactjs testing jestjs react-testing-library

这是我第一次编写测试。我正在为使用钩子编写的ReactJS应用编写测试,并使用Jestreact-testing-library进行测试。

这是我的功能组件:

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:无法读取null的属性“ getBarcode”

我不知道该如何解决?

1 个答案:

答案 0 :(得分:1)

期望是错误的,因为console.log并未在任何地方被调用。对console之类的global.console = ...对象进行模拟是一种不好的做法,因为它在测试之间仍然存在,并且可能破坏依赖它的事物,包括测试运行器本身。

项目code的密钥不一致,它以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');