dlms-protocol
Version:
DLMS Protocol parser for JavaScript
77 lines (61 loc) • 2.71 kB
JavaScript
import DataNotification from "../src/messages/DataNotification";
import DlmsDatas from "../src/typesDLMS/DlmsDatas";
jest.mock("../src/typesDLMS/DlmsDatas");
describe("DataNotification class", () => {
beforeEach(() => {
DlmsDatas.factory.mockClear();
});
const mockNotificationBody = {
insertData: jest.fn(),
};
DlmsDatas.factory.mockReturnValue(mockNotificationBody);
test("should initialize with default values when no bytes are provided", () => {
const dataNotification = new DataNotification();
expect(dataNotification.longInvokeId).toBe('');
expect(dataNotification.dateTimeValue).toBeNull();
expect(dataNotification.notificationBody).toBeNull();
expect(dataNotification.value).toEqual([]);
});
test("should correctly parse bytes and set properties", () => {
const bytes = [
0x01, // Message type
0x12, 0x34, 0x56, 0x78, // Long Invoke ID
0x00, // Reserved or irrelevant byte
0x01, // DlmsData type
0xA1, 0xB2, 0xC3, // Notification body
];
const dataNotification = new DataNotification(bytes);
expect(dataNotification.longInvokeId).toBe('12345678');
expect(dataNotification.notificationBody).toEqual(mockNotificationBody);
expect(mockNotificationBody.insertData).toHaveBeenCalledWith([0x01, 0xA1, 0xB2, 0xC3]);
expect(dataNotification.value).toEqual(bytes);
});
test("should return the correct byte array with getBytes()", () => {
const bytes = [
0x01, 0x12, 0x34, 0x56, 0x78, 0x00, 0x01, 0xA1, 0xB2, 0xC3,
];
const dataNotification = new DataNotification(bytes);
const result = dataNotification.getBytes();
expect(result).toEqual(bytes);
});
test("should return the correct hexadecimal string with getHexString()", () => {
const bytes = [
0x01, 0x12, 0x34, 0x56, 0x78, 0x00, 0x01, 0xA1, 0xB2, 0xC3,
];
const dataNotification = new DataNotification(bytes);
const hexString = dataNotification.getHexString();
const expectedHex = bytes
.map(byte => byte.toString(16).toUpperCase().padStart(2, '0'))
.join(' ');
expect(hexString).toBe(expectedHex);
});
test("should throw an error if DlmsDatas.factory fails", () => {
DlmsDatas.factory.mockImplementation(() => {
throw new Error("Factory error");
});
const bytes = [
0x01, 0x12, 0x34, 0x56, 0x78, 0x00, 0x01, 0xA1, 0xB2, 0xC3,
];
expect(() => new DataNotification(bytes)).toThrow("Factory error");
});
});