English 中文(简体)
如何在Jest进行模拟
原标题:How to mock functions in Jest

我有两个简单的构成部分。 我是用 j子为他们撰写考试。 在我点击货币体系时,我想测试一下,有关阵列应当添加到选定国家。 您可以看到,我通过<条码>,作为货币的推进剂。 因此,我也想 mo弄它。

货币轨道。

import { useEffect, useState } from "react";
import { currencies } from "../constants";
import { Currency } from "../types";
import CurrencyItem from "./CurrencyItem";

const CurrencySelector = () => {
  const initialSelected = () => {
    const storedCurrencies = sessionStorage.getItem("currencies");
    return storedCurrencies ? JSON.parse(storedCurrencies) : [];
  };

  const [selected, setSelected] = useState<Currency[]>(initialSelected);

  const handleCurrencyToggle = (currency: Currency) => {
    const isSelected = selected.some(
      (selectedCurrency) => selectedCurrency.name === currency.name
    );

    if (isSelected) {
      setSelected((prevSelected) =>
        prevSelected.filter(
          (selectedCurrency) => selectedCurrency.name !== currency.name
        )
      );
    } else {
      setSelected((prevSelected) => [...prevSelected, currency]);
    }
  };

  useEffect(() => {
    sessionStorage.setItem("currencies", JSON.stringify(selected));
  }, [selected]);

  return (
    <div className="currency-selector">
      <div className="selected-currencies currency-items">
        {selected.length > 0 ? (
          selected.map((currency: Currency, index: number) => (
            <div
              data-testid="selected-currency"
              key={index}
              className="selected-currency currency"
            >
              <span>{currency.name}</span>
              <button
                className="unselect-currency"
                onClick={() => handleCurrencyToggle(currency)}
              >
                x
              </button>
            </div>
          ))
        ) : (
          <div data-testid="no-selected-currencies" className="no-currencies">
            No selected currencies
          </div>
        )}
      </div>
      <div className="currency-items">
        {currencies.map((currency: Currency, index: number) => (
          <CurrencyItem
            data-testid={`currency-item-${index}`}
            key={index}
            currency={currency}
            onClick={() => handleCurrencyToggle(currency)}
            isSelected={selected.some(
              (selectedCurrency) => selectedCurrency.name === currency.name
            )}
          />
        ))}
      </div>
    </div>
  );
};

export default CurrencySelector;

货币估算值。

import { Currency } from "../types";

const CurrencyItem = ({
  currency,
  onClick,
  isSelected,
}: {
  currency: Currency;
  onClick: () => void;
  isSelected: boolean;
}) => {
  const handleCheckboxChange = () => {
    onClick();
  };

  return (
    <div data-testid="currency-item" onClick={onClick} className="currency">
      <label>
        <input onChange={handleCheckboxChange} checked={isSelected} type="checkbox" />
        <span className="checkbox-container"></span>
      </label>
      <span>{currency.name}</span>
    </div>
  );
};

export default CurrencyItem;

货币阵列:

import { Currency } from "../types";

export const currencies: Currency[] = [
  {
    name: "EUR",
  },
  {
    name: "PLN",
  },
  {
    name: "GEL",
  },
  {
    name: "DKK",
  },
  {
    name: "CZK",
  },
  {
    name: "GBP",
  },
  {
    name: "SEK",
  },
  {
    name: "USD",
  },
  {
    name: "RUB",
  },
];

我的考验:

  it("adds currency to select list", () => {
    const handleCurrencyToggle = jest.fn()
    const { getByTestId: getByTestId2 } = render(
        <CurrencySelector />
      );
    const { getByTestId } = render(
      <CurrencyItem
        key={1}
        currency={currencies[0]}
        onClick={() => () => {
          handleCurrencyToggle();
        }}
        isSelected={true}
      />
    );
    
    const currencyItem = getByTestId("currency-item");
    fireEvent.click(currencyItem);

    const selectItem = getByTestId2("selected-currency").textContent
    expect(selectItem).toBe("EUR");
  });
});

我知道这并不正确,但我要指导我如何篡改真正处理Toggle职能。

问题回答

为了适当测试货币轨迹和货币元件之间的一体化,你可以篡改货币轨元件中的处理能力图格尔功能,并确保在点击货币元件时使用正确的参数。

import CurrencySelector from "./CurrencySelector";
import { currencies } from "../constants";

describe("CurrencySelector", () => {
  it("adds currency to select list", () => {
    const mockedHandleCurrencyToggle = jest.fn();

    // Mock the handleCurrencyToggle function
    jest.mock("../CurrencySelector", () => ({
      __esModule: true,
      default: () => <div data-testid="currency-selector" />,
      handleCurrencyToggle: mockedHandleCurrencyToggle,
    }));

    const { getByTestId } = render(
      <CurrencyItem
        key={1}
        currency={currencies[0]}
        onClick={() => mockedHandleCurrencyToggle()}
        isSelected={true}
      />
    );

    const currencyItem = getByTestId("currency-item");
    fireEvent.click(currencyItem);

    // Ensure that handleCurrencyToggle is called with the correct parameters
    expect(mockedHandleCurrencyToggle).toHaveBeenCalledWith(currencies[0]);
  });
});                                                                                                                                                             

处理过的Toggle功能被模拟,改为模拟 HandleCurrency Toggle in the MonetarySelector composition. 然后,在你对货币体系的测试中,如果将湿租赁HandleCurrency Toggle称作预期参数,你可以检查。

以上编码假定,货币动力部件进口从同一档案中处理Currency Toggle。 如果从不同档案中进口,你应调整最小。 因此, path路。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签