simple-in-memory-queue
Version:
A simple in-memory queue, for nodejs and the browser, with consumers for common usecases.
65 lines • 3.28 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const sleep_1 = require("../../utils/sleep");
const createQueueWithDebounceConsumer_1 = require("./createQueueWithDebounceConsumer");
describe('createQueueWithDebounceConsumer', () => {
beforeEach(() => jest.resetAllMocks());
it('should invoke the consumer only after the gap between events has passed the threshold', () => __awaiter(void 0, void 0, void 0, function* () {
const mockedConsumer = jest.fn();
const queue = (0, createQueueWithDebounceConsumer_1.createQueueWithDebounceConsumer)({
gap: { milliseconds: 100 },
consumer: mockedConsumer,
});
// add to queue
queue.push('a');
// prove not invoked yet
expect(mockedConsumer).not.toHaveBeenCalled();
// add to queue again
queue.push('b');
// prove not invoked yet
expect(mockedConsumer).not.toHaveBeenCalled();
// wait 100ms
yield (0, sleep_1.sleep)(110);
// prove invoked
expect(mockedConsumer).toHaveBeenCalled();
expect(mockedConsumer).toHaveBeenCalledTimes(1);
expect(mockedConsumer).toHaveBeenCalledWith({ items: ['a', 'b'] });
}));
it('should invoke the consumer with only the events from the new batch, when more than one successive batch', () => __awaiter(void 0, void 0, void 0, function* () {
const mockedConsumer = jest.fn();
const queue = (0, createQueueWithDebounceConsumer_1.createQueueWithDebounceConsumer)({
gap: { milliseconds: 100 },
consumer: mockedConsumer,
});
// add to queue
queue.push('a');
queue.push('b');
// wait 100ms to allow it to be invoked
yield (0, sleep_1.sleep)(110);
// prove invoked
expect(mockedConsumer).toHaveBeenCalled();
expect(mockedConsumer).toHaveBeenCalledTimes(1);
expect(mockedConsumer).toHaveBeenLastCalledWith({ items: ['a', 'b'] });
// add more to the queue
queue.push('c');
queue.push('d');
queue.push('e');
// prove not invoked again yet
expect(mockedConsumer).toHaveBeenCalledTimes(1); // still only once
// wait 100ms to allow it to be invoked
yield (0, sleep_1.sleep)(110);
// prove invoked with only the new batch of data
expect(mockedConsumer).toHaveBeenCalledTimes(2);
expect(mockedConsumer).toHaveBeenLastCalledWith({ items: ['c', 'd', 'e'] });
}));
});
//# sourceMappingURL=createQueueWithDebounceConsumer.test.js.map