Search code examples
jestjsdiscord.jsts-jest

ReferenceError: fetch is not defined when importing from discord.js (v14) in ts-jest tests


I'm running the following ts-jest code:

import { Client, GatewayIntentBits } from "discord.js";

let client: Client;
beforeEach(async () => {
  client = new Client({ intents: GatewayIntentBits.Guilds });
});

describe("guildCreate", () => {
  it("empty DB: call with new options", async () => {
    // check before 1st fn call
    expect(client.guilds.cache.size).toEqual(0);
  });
});

I keep getting the following error:

Test suite failed to run
                                                                                                        
ReferenceError: fetch is not defined

  at Object.<anonymous> (node_modules/@discordjs/rest/src/web.ts:3:20)
  at Object.<anonymous> (node_modules/discord.js/src/client/BaseClient.js:4:18)

Initialising the Client works fine in my code. But, fails when in jest for discordJs (v14).


Solution

  • It turns out that the answer is to add the following code to my jest.config.js file:

    globals: { fetch: global.fetch },