2

这是我第一次写测试。我正在为使用钩子编写的 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”

我不知道我该如何解决这个问题?

4

1 回答 1

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');
于 2019-02-14T12:22:55.513 回答