|
| 1 | +import {PACKET_TYPE, PROPERTY} from '../../enums'; |
| 2 | +import {PacketPublish} from '../publish'; |
| 3 | +import {MqttDecoder} from '../../MqttDecoder'; |
| 4 | + |
| 5 | +test('can create a packet', () => { |
| 6 | + const packet = PacketPublish.create('topic', 0, {}, Buffer.from([1, 2, 3])); |
| 7 | + expect(packet.b >> 4).toBe(PACKET_TYPE.PUBLISH); |
| 8 | + expect(packet.t).toBe('topic'); |
| 9 | + expect(packet.i).toBe(0); |
| 10 | + expect(packet.p).toEqual({}); |
| 11 | + expect(packet.d).toEqual(Buffer.from([1, 2, 3])); |
| 12 | +}); |
| 13 | + |
| 14 | +test('can serialize a basic packet', () => { |
| 15 | + const packet1 = PacketPublish.create('topic', 0, {}, Buffer.from([1, 2, 3])); |
| 16 | + const buf = packet1.toBuffer(5); |
| 17 | + const decoder = new MqttDecoder(); |
| 18 | + decoder.version = 5; |
| 19 | + decoder.push(buf); |
| 20 | + const packet2 = decoder.parse()! as PacketPublish; |
| 21 | + expect(packet2.b).toBe(packet1.b); |
| 22 | + expect(packet2.t).toBe('topic'); |
| 23 | + expect(packet2.p).toEqual({}); |
| 24 | + expect(packet2.d).toEqual(Buffer.from([1, 2, 3])); |
| 25 | + expect(packet2).toEqual(packet1); |
| 26 | +}); |
| 27 | + |
| 28 | +test('can encode packet with QoS = 1', () => { |
| 29 | + const packet1 = PacketPublish.create('topic', 1, {}, Buffer.from([1, 2, 3])); |
| 30 | + packet1.setQualityOfService(1); |
| 31 | + const buf = packet1.toBuffer(5); |
| 32 | + const decoder = new MqttDecoder(); |
| 33 | + decoder.version = 5; |
| 34 | + decoder.push(buf); |
| 35 | + const packet2 = decoder.parse()! as PacketPublish; |
| 36 | + expect(packet2.b).toBe(packet1.b); |
| 37 | + expect(packet2.qualityOfService()).toBe(1); |
| 38 | + expect(packet2.t).toBe('topic'); |
| 39 | + expect(packet2.p).toEqual({}); |
| 40 | + expect(packet2.d).toEqual(Buffer.from([1, 2, 3])); |
| 41 | + expect(packet2).toEqual(packet1); |
| 42 | +}); |
| 43 | + |
| 44 | +test('can encode properties', () => { |
| 45 | + const packet1 = PacketPublish.create('topic', 1, { |
| 46 | + [PROPERTY.AssignedClientIdentifier]: 'test', |
| 47 | + [PROPERTY.UserProperty]: [ |
| 48 | + ['test', 'test'], |
| 49 | + ], |
| 50 | + }, Buffer.from([1, 2, 3])); |
| 51 | + packet1.setQualityOfService(1); |
| 52 | + const buf = packet1.toBuffer(5); |
| 53 | + const decoder = new MqttDecoder(); |
| 54 | + decoder.version = 5; |
| 55 | + decoder.push(buf); |
| 56 | + const packet2 = decoder.parse()! as PacketPublish; |
| 57 | + expect(packet2.b).toBe(packet1.b); |
| 58 | + expect(packet2.qualityOfService()).toBe(1); |
| 59 | + expect(packet2.t).toBe('topic'); |
| 60 | + expect(packet2.p).toEqual({ |
| 61 | + [PROPERTY.AssignedClientIdentifier]: 'test', |
| 62 | + [PROPERTY.UserProperty]: [ |
| 63 | + ['test', 'test'], |
| 64 | + ], |
| 65 | + }); |
| 66 | + expect(packet2.d).toEqual(Buffer.from([1, 2, 3])); |
| 67 | + expect(packet2).toEqual(packet1); |
| 68 | +}); |
0 commit comments