const EventEmitter = require('events')
const assert = require('assert')
const inject = require('../lib/plugins/digging')
describe('digging plugin death handler', () => {
function createMockBot () {
const bot = new EventEmitter()
bot.targetDigBlock = null
bot.targetDigFace = null
bot.lastDigTime = null
bot._client = { write: () => {} }
bot.entity = {
position: { x: 0, y: 0, z: 0, offset: () => ({ x: 0, y: 0, z: 0, distanceTo: () => 0 }) },
isInWater: false,
onGround: true,
eyeHeight: 1.62,
effects: {}
}
bot.heldItem = null
bot.game = { gameMode: 'survival' }
bot.inventory = { slots: [] }
bot.getEquipmentDestSlot = () => 5
bot.swingArm = () => {}
bot.world = { raycast: () => null }
return bot
}
it('should not throw when death is emitted and no digging is in progress', () => {
const bot = createMockBot()
inject(bot)
assert.doesNotThrow(() => {
bot.emit('death')
})
})
it('should not throw when death is emitted and stopDigging throws', () => {
const bot = createMockBot()
inject(bot)
bot.stopDigging = () => {
throw new Error('unexpected state error')
}
assert.doesNotThrow(() => {
bot.emit('death')
})
})
it('should not throw when death is emitted with problematic event listeners', () => {
const bot = createMockBot()
inject(bot)
bot.on('diggingAborted', () => {})
bot.on('diggingCompleted', () => {})
const origRemoveAll = bot.removeAllListeners.bind(bot)
bot.removeAllListeners = (event) => {
if (event === 'diggingAborted') {
throw new Error('Cannot read properties of undefined')
}
return origRemoveAll(event)
}
assert.doesNotThrow(() => {
bot.emit('death')
})
})
it('should clean up digging listeners on death when digging is active', () => {
const bot = createMockBot()
inject(bot)
bot.on('diggingAborted', () => {})
bot.on('diggingCompleted', () => {})
assert.ok(bot.listenerCount('diggingAborted') > 0)
assert.ok(bot.listenerCount('diggingCompleted') > 0)
bot.emit('death')
assert.strictEqual(bot.listenerCount('diggingAborted'), 0)
assert.strictEqual(bot.listenerCount('diggingCompleted'), 0)
})
})