使用Jest创建测试或模拟DiscordJS Fetch/Catch

djp7away  于 2023-06-20  发布在  Jest
关注(0)|答案(1)|浏览(149)

我创建了一个DiscordJS Bot,并尝试使用JestJS实现自动化测试。下面是我尝试创建测试的函数之一:

/**
 * @param {Object} client - Discord Client
*/
export const getSpecificGuild = async (client) => {
    let guild = await client.guilds.fetch(GUILD_ID).catch(() => { return false });

    if (!guild) return false;

    return guild;
}

我现在无法解决的问题是尝试为这两种场景创建测试:

  • 正在检索有效的军团(返回军团对象)。
  • Guild检索无效(返回***false***)。

下面是我的sample.test.js文件的当前版本:

describe('Test getSpecificGuild Function', () => {
    beforeEach(() => {
        jest.clearAllMocks();
    });

    const mockGuild = {
        ...
    }

    const mockClient = {
        guilds: {
            fetch: jest.fn().mockReturnValueOnce({
                catch: jest.fn().mockReturnValueOnce(false)
            })
        }
    }

    it(`should return the guild object if the guild doesn't exist.`, async () => {
        expect(await getSpecificGuild(mockClient)).toBe(false);
    });

    it(`should return the guild object if the guild does exist.`, async () => {
        expect(await getSpecificGuild(mockClient)).resolves.toBe(mockGuild);
    });
});

我发现很难模拟程序的fetch/catch部分。因为如果检索成功,fetch就会结束,并且不会继续到catch部分,除非它运行错误(就像try/catch一样)。运行测试后,将显示以下内容:

✓ should return the guild object if the guild doesn't exist. (1 ms)
✕ should return the guild object if the guild does exist.

TypeError: Cannot read properties of undefined (reading 'catch')

let guild = await client.guilds.fetch(GUILD_ID).catch(() => { return false });
                                               ^

如果我的Jest实现是错误的,请原谅我,我真的很感激大家的帮助。

thtygnil

thtygnil1#

catch是Promise示例上的一个方法,你不应该嘲笑它。你应该只模仿guilds.fetch()
另外,你的getSpecificGuild()函数目前不接受公会ID,所以我更新了它。我认为client.guilds.fetch()不会返回falsy值,所以你也可以删除它:

export const getSpecificGuild = async (guildId, client) => {
  let guild = await client.guilds.fetch(guildId).catch(() => {
    return false;
  });

  return guild;
};

要模拟此情况,您需要更新mockClient。您可以根据提供的公会ID更改fetch函数的行为,并有条件地返回已解决的Promise或已拒绝的Promise。

describe('Test getSpecificGuild Function', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  const mockGuild = { ... };
  const VALID_GUILD_ID = '804214837842837';

  const mockClient = {
    guilds: {
      fetch: jest.fn().mockImplementation((guildId) => {
        // Valid guild retrieval
        if (guildId === VALID_GUILD_ID) 
          return Promise.resolve(mockGuild);

        // Invalid guild retrieval
        else
          return Promise.reject(new Error('Guild not found'));
      }),
    },
  };

  it(`should return the guild object if the guild does exist.`, async () => {
    // you don't need "resolves.toBe()"" with await
    expect(await getSpecificGuild(VALID_GUILD_ID, mockClient)).toBe(mockGuild);
  });

  it(`should return false if the guild doesn't exist.`, async () => {
    expect(await getSpecificGuild('12345', mockClient)).toBe(false);
  });
});

相关问题