reactjs - 如何使用带有 typescript 的手动模拟, react 和开玩笑?

标签 reactjs typescript mocking ts-jest react-tsx

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

usePrice.ts

export default function usePrice() {
  return 1337;
}

PriceTag.tsx 中:

import React from 'react';
import usePrice from './usePrice';

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

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

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

__mocks__/usePrice.ts

let price = 58008;

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

export default function usePrice() {
  return price;
}

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';

关于reactjs - 如何使用带有 typescript 的手动模拟, react 和开玩笑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67000607/

相关文章:

javascript - Typescript 编译成的 javascript "namespace"模式的名称是什么?

额外类型条件的 Typescript key

angular - 模拟类以使用 Typescript 和 Jest 进行测试

java - 用 mockito 模拟单例

javascript - 无法将 react 模式呈现为可重用组件

javascript - 在 React 中,在展开时为居中元素设置动画

javascript - 如何计算用户在 React Native 中花费的特定屏幕上的时间

javascript - 为什么在无状态函数表达式中中断 'console.log'?

java - Spring 网络流程 : setting request parameter for JUnit test

c# - Moq - 无法遍历隐藏的 IEnumerable