微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在打字稿、反应和开玩笑中使用手动模拟?

如何解决如何在打字稿、反应和开玩笑中使用手动模拟?

我正在尝试使用 jest 来模拟 React 组件使用的钩子的返回值,但无法让它工作。考虑价格标签组件。它所做的只是呈现从 usePrice 挂钩返回的价格。

// In usePrice.ts
export default function usePrice() {
  return 1337;
}

// In PriceTag.tsx
import React from 'react';
import usePrice from './usePrice';

export default function PriceTag() {
  const price = usePrice();

  return <p>Price: {price}</p>
}

在测试中,我断言显示了正确的价格。由于我想为此组件创建多个测试,因此 setPrice 助手用于为每个测试设置下一个返回值。

// In __mocks__/usePrice.ts
let price = 58008;

export function setPrice(newPrice) {
  price = newPrice;
}

export default function usePrice() {
  return price;
}

// In PriceTag.test.tsx
import { render } from '@testing-library/react';
import React from 'react';
import PriceTag from './PriceTag';
import { setPrice } from './__mocks__/usePrice';

jest.mock('./usePrice');

describe('PriceTag',() => {
  it('renders the price',() => {
    setPrice(100);
    const { getByText } = render(<PriceTag />);

    const textEl = getByText('Price: 100');

    expect(textEl).toBeInTheDocument();
  });
});

当我运行测试时,我得到以下失败:

    TestingLibraryElementError: Unable to find an element with the text: Price: 100. This Could be because the text is broken up by multiple elements. In this case,you can pro
vide a function for your text matcher to make your matcher more flexible.

    <body>
      <div>
        <p>
          Price:
          58008
        </p>
      </div>
    </body>

      11 |     const { getByText } = render(<PriceTag />);
      12 |
    > 13 |     const textEl = getByText('Price: 100');
         |                    ^
      14 |
      15 |     expect(textEl).toBeInTheDocument();
      16 |   });

正在使用模拟,因为 58008 在 DOM 中呈现。但是,我希望返回 100。我相信这是由于 Jest 提升变量的方式,但如果我能让它工作,那将非常有用。

代码直接受到他们模拟 fs 模块的示例的启发:https://jestjs.io/docs/manual-mocks#examples

解决方法

我相信您看到的问题是由于您正在导入模拟本身。

import { setPrice } from './__mocks__/usePrice';

Jest 希望您导入实际模块。尝试将其更改为

import { setPrice } from './usePrice';

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?