首页 > 解决方案 > 对我的 discord.js 机器人进行单元测试时未定义的属性(测试本身通过,但随后出现错误)

问题描述

我正在尝试为我的 discord.js 机器人设置单元测试,但是npm test在终端中运行时,在测试通过时,仍然会出错。

这是正在通过的测试的图像,随后出现错误: https ://i.imgur.com/m2EOuxc.png

我需要在测试中修复这个错误,同时仍然让机器人能够运行。

我试图完全删除错误中引用的行(以及与该特定行有关的行)

  jsfiles.forEach((f, i) => {
    let props = require(`./cmds/${f}`)
    bot.commands.set(props.help.name, props)
  })

删除它解决了测试问题,但导致机器人无法正常运行(它没有加载命令;意思是机器人无法与之交互),这不是这里的目标。

我还检查了文件夹中的每个文件都cmds

module.exports.help = {
  name: '<name of the command I use for each command>'
} 

这是我的bot.js文件中包含问题的部分。

// Loads the commands for the bot:
fs.readdir('./cmds/', (err, files) => {
  if (err) console.error(err)

  let jsfiles = files.filter(f => f.split('.').pop() === 'js')
  if (jsfiles.length <= 0) {
    console.log('No commands to load!')
    return
  }

  if (testingSettings) {
    console.log(`Loading ${jsfiles.length} commands!`)
  }

  // This is the problem referenced above: 
  // ----------------------------------------------------------------------
  jsfiles.forEach((f, i) => {
    let props = require(`./cmds/${f}`)
    bot.commands.set(props.help.name, props)
  })
  // ----------------------------------------------------------------------

})

这是我在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']);
});

如果需要的话。这是用于连接的函数、变量和导出bot.js方法bot.test.js

变量(在bot.js文件中)

const testingSettings = false

功能(在bot.js文件中)

function checkingTesting (testingSettings, name) {
  if (testingSettings) {
    return testSettings[name]
  } else if (!testingSettings) {
    return process.env[name]
  }  
}

导出(在bot.js文件中)

module.exports = {
  // Exporting functions
  checkingTesting: checkingTesting,


  // Exporting variables
  testingSettings: testingSettings,
}

标签: node.jsunit-testingjestjsbotsdiscord.js

解决方案


在您的命令文件中,似乎没有help. module.exports当您尝试阅读help.name时,它会抛出您的错误,因为它help是未定义的。

检查以确保您module.exports.help在每个命令文件中都进行了声明。


推荐阅读