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

时间:2021-04-08 08:58:20

标签: reactjs typescript mocking ts-jest react-tsx

我正在尝试使用 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

1 个答案:

答案 0 :(得分:2)

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

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

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

import { setPrice } from './usePrice';
相关问题