首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用react测试运行jest测试时出错.库

使用react测试运行jest测试时出错.库
EN

Stack Overflow用户
提问于 2019-02-14 11:35:04
回答 1查看 1.9K关注 0票数 2

这是我第一次写测试。我正在为用钩子编写的ReactJS应用程序编写测试,并使用取笑反应-测试-库进行测试。

这是我的功能组件:

代码语言:javascript
复制
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;

以及测试文件:

代码语言:javascript
复制
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

我不知道怎样才能解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-14 12:22:55

预期是错误的,因为console.log在任何地方都没有被调用。模拟console对象(如global.console = ... )是一种糟糕的做法,因为它在测试之间持续存在,并且可以破坏依赖它的东西,包括测试运行程序本身。

它与项目code密钥不一致,它以barcode的形式提供。

除非提供默认值,否则预期上下文值为undefined。它应该在试验中提供。

可能应该是:

代码语言:javascript
复制
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');
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54689470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档