我已经创建了一个DiscordJS机器人,我正在try 使用JestJS实现自动化测试.以下是我try 用来创建测试的函数之一:
/**
* @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;
}
我现在不能解决的问题是try 为这两种场景创建测试:
- 检索有效的Guild(返回Guild对象).
- 无效的Guild检索(返回100).
以下是我的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实现有误,请原谅,我将非常感谢大家的帮助.