uci-utils-obj-buffer/test/test.js

57 lines
1.7 KiB
JavaScript

import { expect } from 'chai'
import ObjBuffer from '../src/obj-buffer.js'
const obj = { cmd: 'test', _header: { name: 'a # name', id: 'i12345' }, arg: 5 }
const ser = '66_%#_{"cmd":"test","_header":{"name":"a # name","id":"i12345"},"arg":5}'
const otb = new ObjBuffer()
const event = 'decoded'
describe('Object to Buffer encode/decode', function () {
it('Should stringify and encode a message/object', async function () {
expect(await otb.encode(obj)).to.equal(ser)
})
it('Should encode and decode a message', function () {
return new Promise(async (resolve, reject) => {
otb.once(event, mes => {
// console.log('message received', mes)
expect(mes).to.deep.equal(obj)
resolve()
})
const ser = await otb.encode(obj)
// console.log('encoded', ser)
otb.decode(ser)
})
})
it('encode throws an error if object contains the delmiter', async function () {
obj._header.name = '_%#_'
return otb.encode(obj)
.then(res => {
expect.fail('no error was thrown for')
})
.catch(error => {
// console.log('error', error)
expect(error).to.be.an('error')
}
)
})
it('Should queue message if paused and emit if resumed', function () {
return new Promise(async (resolve, reject) => {
otb.once(event, mes => {
// console.log('queued message', mes)
expect(mes).to.deep.equal(obj)
resolve()
})
obj._header.name = 'name'
const ser = await otb.encode(obj)
otb.pause()
otb.decode(ser)
// console.log(otb.state, otb.queue[0])
expect(otb.queue[0]).to.deep.equal(obj)
otb.resume()
})
})
})