Node.js 单元测试my discord.js bot时未定义属性(测试本身已通过,但随后出现错误)
我正在尝试为discord.js bot设置单元测试,但是在终端中运行Node.js 单元测试my discord.js bot时未定义属性(测试本身已通过,但随后出现错误),node.js,unit-testing,jestjs,bots,discord.js,Node.js,Unit Testing,Jestjs,Bots,Discord.js,我正在尝试为discord.js bot设置单元测试,但是在终端中运行npm test时,当测试通过时,仍然会出现错误 这是通过测试的图像,后面是错误: 我需要在测试中修复此错误,同时使bot仍能正常工作 我已尝试完全删除错误中引用的行(以及与该特定行相关的行) 删除此选项解决了测试问题,但导致bot无法正常运行(它没有加载命令;这意味着无法与bot交互),这不是本文的目标 我还检查了文件夹cmds中的每个文件是否以 module.exports.help = { name: '<n
npm test
时,当测试通过时,仍然会出现错误
这是通过测试的图像,后面是错误:
我需要在测试中修复此错误,同时使bot仍能正常工作
我已尝试完全删除错误中引用的行(以及与该特定行相关的行)
删除此选项解决了测试问题,但导致bot无法正常运行(它没有加载命令;这意味着无法与bot交互),这不是本文的目标
我还检查了文件夹cmds
中的每个文件是否以
module.exports.help = {
name: '<name of the command I use for each command>'
}
这是我在bot.test.js
文件中的所有代码
const {
// Functions
checkingTesting,
// Variables
testingSettings,
} = require('./bot')
test('checking to see if testing-mode is on', () => {
expect(checkingTesting(testingSettings, 'token')).toBe(process.env['token']);
});
const testingSettings = false
function checkingTesting (testingSettings, name) {
if (testingSettings) {
return testSettings[name]
} else if (!testingSettings) {
return process.env[name]
}
}
module.exports = {
// Exporting functions
checkingTesting: checkingTesting,
// Exporting variables
testingSettings: testingSettings,
}
如果需要的话。这是用于将bot.js
连接到bot.test.js
的函数、变量和导出方法:
变量(在bot.js
文件中)
函数(在bot.js
文件中)
导出(在bot.js
文件中)
在命令文件中,似乎没有
module.exports的help
属性。当您尝试读取help.name
时,它会抛出错误,因为help
未定义
检查以确保在每个命令文件中声明module.exports.help
props.help
未定义。所需文件的导出obj为空、没有帮助
,或者其他一些不可预见的事件
一个好的做法是在使用对象键之前始终检查它是否存在
if (props && props.help) {
bot.commands.set(props.help.name, props)
} else {
//throw or handle error here
}
我检查了每个文件,所有文件都有这个``module.exports.help={name:'}``我试图删除cmds
文件夹中的所有文件。它起作用了,但只是因为以下代码:``让jsfiles=files.filter(f=>f.split('.').pop()=='js'),如果(jsfiles.length您是否检查了/cmds/
中的每个文件?是的,现在我还仔细检查了控制台的caseLogprops
。这是正常运行bot时props
的console.log的图像(node bot.js
)使用此代码进行测试后,无法在bot.js
文件中记录console.log内容。我可以毫无错误地运行测试。我想知道,我可以在else语句中输入什么,因为测试时我无法console.log。感谢b忽略此错误,您应该确保每个文件中都包含您期望的内容。如果您不知道我甚至不知道你自己的代码是做什么的,你怎么能希望测试它?@AndreasG.DPetersen抱歉,fella。我没有开玩笑。但是试试看:有些人在console.log上取得了成功。其他人没有。如果你找到了“调试”,这可能是最好的选择解决方案u可以与jest一起使用。@Joshrobot首先,没有人声明忽略错误。else案例明确说明如何处理错误。无论是日志事件、退出过程,还是开发人员决定的。其次,“您应该确保每个文件中都有您期望的内容”,他在其OP中声明:“我还检查了文件夹cmds中的每个文件是否以module.exports.help结尾”。第三,不要期望您的输入按预期工作!务必检查并处理最适合的else情况。
module.exports = {
// Exporting functions
checkingTesting: checkingTesting,
// Exporting variables
testingSettings: testingSettings,
}
if (props && props.help) {
bot.commands.set(props.help.name, props)
} else {
//throw or handle error here
}