Hylle
Hylle

Reputation: 1117

Jest is not using mock for node_module?

I am mocking socket.io-client. I create the mock file in path <root>/__mocks__/socket.io-client.js But when I am running the test, it doesn't seem like jest is using the mock. What am I doing wrong?

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();
});

Upvotes: 0

Views: 138

Answers (1)

Hylle
Hylle

Reputation: 1117

The issue was that I have a jsconfig.json file where I set my baseUrl or root directory to be the /src folder. This is to enable absolute imports in my react project.

jsconfig.json

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

Jest is setup to look in the root directory for the __mocks__ directory, but since it is in root directory, and not in /src, Jest would not pick up the mock.

Simply moving the __mocks__ directory to the /src folder fixed the issue.

Upvotes: 1

Related Questions