开玩笑,如何模拟 ES6 模块的命名导出?

问题描述 投票:0回答:1

似乎我以前能够让它工作,但现在我找不到我的旧代码。我一直在寻找这个问题寻求帮助,但到目前为止我无法让模拟工作。

我有这个 ES6 模块:

export default "default"

export const getCatFact = () => ({fact: "cats are quadrupeds"}); 

该测试组件使用的是:

import React, { useContext } from "react";
import { getCatFact } from "./CatService";

const Component = () => {
  
  const {fact} = getCatFact(); 
    return <div data-testid="my-div">{fact}</div>
}

export default Component;

如果我尝试像这样嘲笑......就像安迪接受的答案:


import React from "react";
import { render, screen } from "@testing-library/react";
import '@testing-library/jest-dom'
import Component from "./Component";


test("mock an es6 module", async () => {
    const mockCatFact = jest.fn();

    mockCatFact.mockImplementation(() => ({fact: "mocked"}));
    
    
    jest.mock('./CatService', () => ({
        __esModule: true, 
        default: "mockedDefaultExport",
        getCatFact: mockCatFact
      }));
    
    
    render(
        <Component />
    );
    
    const myDiv = await screen.findByTestId("my-div")
    expect(myDiv).toHaveTextContent("mocked");//Fails! value not mocked
});

我已经尝试过类似于 falsarella 的答案:

import React from "react";
import { render, screen } from "@testing-library/react";
import '@testing-library/jest-dom'
import Component from "./Component";
import { getCatFact } from "./CatService";


test("mock an es6 module", async () => {
   getCatFact.mockImplementation(() => ({fact: "mocked"}));
    // get me "TypeError: _CatService.getCatFact.mockImplementation is not a function"
    
    render(
        <Component />
    );
    
    const myDiv = await screen.findByTestId("my-div")
    expect(myDiv).toHaveTextContent("mocked");//Fails! value not mocked
});

但在这两种情况下,我得到的是未模拟的值。该代码可在此存储库中找到。 有人能看出我做错了什么吗?

jestjs mocking
1个回答
0
投票

事实证明,您不再需要编写一个工厂函数来返回带有

__esModule: true,
的模拟模块。或者如果可以这样做,我就做错了。

这篇文章展示了一种更简单的方法。 🎆 您可以

import * as someModuleAlias from "./myModule"
,然后使用
someModuleAlias.myFxn = jest.fn(() => //mock implementation here
模拟命名的导出函数。 例如:

import { render, screen } from "@testing-library/react";
import '@testing-library/jest-dom'
import * as useCatSvcHook from './CatService';
import Component from "./Component";


test("mock an es6 module", async () => {
    useCatSvcHook.getCatFact = jest.fn(() => ({fact: "mocked"}))
    
    render(
        <Component />
    );
    
    const myDiv = await screen.findByTestId("my-div")
    expect(myDiv).toHaveTextContent("mocked");
});

您还可以监视模块:

test("spyOn an es6 module", async () => {
    const mockHook = jest.spyOn(useCatSvcHook, 'getCatFact');
    mockHook.mockImplementation(() => ({ fact: "mocked" }));

    render(
        <Component />
    );

    const myDiv = await screen.findByTestId("my-div")
    expect(myDiv).toHaveTextContent("mocked"); // works! 
});

...它可以让您使用

mockHook.mockRestore()
恢复原始模块行为 - 举出一种方法。 我已经更新了我的存储库希望它能对某人有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.