【问题标题】:Jest is not using mock for node_module?Jest 没有为 node_module 使用模拟?
【发布时间】:2019-09-30 02:05:00
【问题描述】:

我在嘲笑 socket.io-client。 我在路径<root>/__mocks__/socket.io-client.js 中创建模拟文件 但是当我运行测试时,似乎开玩笑并没有使用模拟。我做错了什么?

socket.io-client.js

let EVENTS = {};

function emit(event, ...args) {
  EVENTS[event].forEach(func => func(...args));
}

const socket = {
  on(event, func) {
    if (EVENTS[event]) {
      return EVENTS[event].push(func);
    }
    EVENTS[event] = [func];
  },
  emit
};

export const io = {
  connect() {
    return socket;
  }
};

// to emulate server emit.
export const serverSocket = { emit };
// cleanup helper
export function cleanup() {
  EVENTS = {};
}

export default io;

chat.test.js

import React from "react";
import mockio, { serverSocket } from "socket.io-client";
import Chat from "components/Chat";
import { render } from "@testing-library/react";

test("App should get messages", () => {
  // first render the app
  const utils = render(<Chat />); // then send a message
  console.log(mockio);
  serverSocket.emit("message", "Hey Wizy!");
  expect(utils.getByText("Hey Wizy!")).toBeTruthy();
});

【问题讨论】:

    标签: reactjs socket.io jestjs babel-jest


    【解决方案1】:

    问题是我有一个 jsconfig.json 文件,我在其中将我的 baseUrl 或根目录设置为 /src 文件夹。这是为了在我的 react 项目中启用绝对导入。

    jsconfig.json

    {
      "compilerOptions": {
        "baseUrl": "src"
      },
      "include": ["src", "__mocks__"]
    }
    

    Jest 设置为在根目录中查找 __mocks__ 目录,但由于它在根目录中,而不是在 /src 中,因此 Jest 不会选择该模拟。

    只需将__mocks__ 目录移动到/src 文件夹即可解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-02
      • 2023-04-02
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 2020-02-23
      • 2021-07-17
      • 2021-09-14
      相关资源
      最近更新 更多