所以我有一个文件,使用模块导出,它有4个字段,其中一个执行字段需要2个args,本质上是一个函数。它不返回任何内容,而是使用discord.js并运行此message.channel.send('Pong');
。我想用玩笑来测试
我如何能:
1-确保以“ Pong”作为参数调用message.channel.send
2-我该如何模拟它,使其实际上不调用它(我只想确保其中的文本像实际的参数是“ Pong”一样,因为由于缺少正确的消息而无法调用它对象)
我可以访问并执行实际命令,但是不确定如何检查message.channel.send
的内容。我无法重建消息对象,因此可能还需要模拟。
我正在使用discord.js,但这并不重要。
我还必须测试具有返回功能的功能的命令,那么我应该如何处理它们?
答案 0 :(得分:3)
我实际上正在使用Discord.js模拟库,但是在完成之前,您可以执行以下操作:
const Discord = require('discord.js')
// replace this with whatever the execute command is
// e.g. const ping = require('./commands/ping').execute
const ping = async (message, args) => {
message.channel.send('Pong')
}
// a counter so that all the ids are unique
let count = 0
class Guild extends Discord.Guild {
constructor(client) {
super(client, {
// you don't need all of these but I just put them in to show you all the properties that Discord.js uses
id: count++,
name: '',
icon: null,
splash: null,
owner_id: '',
region: '',
afk_channel_id: null,
afk_timeout: 0,
verification_level: 0,
default_message_notifications: 0,
explicit_content_filter: 0,
roles: [],
emojis: [],
features: [],
mfa_level: 0,
application_id: null,
system_channel_id: null
})
this.client.guilds.cache.set(this.id, this)
}
}
class TextChannel extends Discord.TextChannel {
constructor(guild) {
super(guild, {
id: count++,
type: 0
})
this.client.channels.cache.set(this.id, this)
}
// you can modify this for other things like attachments and embeds if you need
send(content) {
return this.client.actions.MessageCreate.handle({
id: count++,
type: 0,
channel_id: this.id,
content,
author: {
id: 'bot id',
username: 'bot username',
discriminator: '1234',
bot: true
},
pinned: false,
tts: false,
nonce: '',
embeds: [],
attachments: [],
timestamp: Date.now(),
edited_timestamp: null,
mentions: [],
mention_roles: [],
mention_everyone: false
})
}
}
class Message extends Discord.Message {
constructor(content, channel, author) {
super(channel.client, {
id: count++,
type: 0,
channel_id: channel.id,
content,
author,
pinned: false,
tts: false,
nonce: '',
embeds: [],
attachments: [],
timestamp: Date.now(),
edited_timestamp: null,
mentions: [],
mention_roles: [],
mention_everyone: false
}, channel)
}
}
const client = new Discord.Client()
const guild = new Guild(client)
const channel = new TextChannel(guild)
// the user that executes the commands
const user = {id: count++, username: 'username', discriminator: '1234'}
describe('ping', () => {
it('sends Pong', async () => {
await ping(new Message('ping', channel, user))
expect(channel.lastMessage.content).toBe('Pong')
})
})
您还需要将testEnvironment: 'node'
放入笑话配置中(请参阅this issue)。
如果您需要获取时间戳等信息,也可以使用Discord.SnowflakeUtil.generate()
生成ID。