bennc-js/tests/buffer-reader.test.ts
Jack Hadrill a93bfc182f
Some checks failed
continuous-integration/drone/push Build is failing
Initial progress
2022-02-01 02:12:49 +00:00

97 lines
2.2 KiB
TypeScript

import { BufferReader } from '../src/buffer-reader'
test('Read a UInt16.', () => {
// Given
const buffer = Buffer.from([0x30, 0x39])
// When
const smartBuffer = new BufferReader(buffer)
// Then
expect(smartBuffer.readUInt16()).toBe(12345)
})
test('Read a UInt32.', () => {
// Given
const buffer = Buffer.from([0x49, 0x96, 0x02, 0xD2])
// When
const smartBuffer = new BufferReader(buffer)
// Then
expect(smartBuffer.readUInt32()).toBe(1234567890)
})
test('Read a buffer.', () => {
// Given
const buffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
// When
const smartBuffer = new BufferReader(buffer)
// Then
expect(smartBuffer.readBuffer(4)).toMatchObject(Buffer.from([0, 1, 2, 3]))
})
test('Cursor is correctly incremented after reading a UInt16.', () => {
// Given
const buffer = Buffer.from([0x30, 0x39, 0x1A, 0x85])
// When
const smartBuffer = new BufferReader(buffer)
// Then
expect(smartBuffer.readUInt16()).toBe(12345)
expect(smartBuffer.readUInt16()).toBe(6789)
})
test('Cursor is correctly incremented after reading a buffer.', () => {
// Given
const buffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
// When
const smartBuffer = new BufferReader(buffer)
// Then
expect(smartBuffer.readBuffer(4)).toMatchObject(Buffer.from([0, 1, 2, 3]))
expect(smartBuffer.readBuffer(4)).toMatchObject(Buffer.from([4, 5, 6, 7]))
})
test('Cursor is correctly incremented after reading a UInt32.', () => {
// Given
const buffer = Buffer.from([0x49, 0x96, 0x02, 0xD2, 0x3A, 0xDE, 0x68, 0xB1])
// When
const smartBuffer = new BufferReader(buffer)
// Then
expect(smartBuffer.readUInt32()).toBe(1234567890)
expect(smartBuffer.readUInt32()).toBe(987654321)
})
test('Seek to position below 0 throws range error.', () => {
// Given
const buffer = Buffer.from([])
// When
const smartBuffer = new BufferReader(buffer)
// Then
expect(() => {
smartBuffer.cursor = -1
}).toThrow(RangeError)
})
test('Seek beyond buffer throws range error.', () => {
// Given
const buffer = Buffer.from([0, 1, 2, 3])
// When
const smartBuffer = new BufferReader(buffer)
// Then
expect(() => {
smartBuffer.cursor = 5
}).toThrow(RangeError)
})