1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00

Introduce function to remove duplication from things that are startable and stoppable

Co-authored-by: Janne Savolainen <janne.savolainen@live.fi>

Signed-off-by: Iku-turso <mikko.aspiala@gmail.com>
This commit is contained in:
Iku-turso 2022-04-11 13:40:42 +03:00 committed by Janne Savolainen
parent d915b2377a
commit 0650d345c7
No known key found for this signature in database
GPG Key ID: 8C6CFB2FFFE8F68A
2 changed files with 105 additions and 0 deletions

View File

@ -0,0 +1,68 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getStartableStoppable } from "./get-startable-stoppable";
describe("getStartableStoppable", () => {
let stopMock: jest.Mock<() => void>;
let startMock: jest.Mock<() => () => void>;
let actual: { stop: () => void; start: () => void };
beforeEach(() => {
stopMock = jest.fn();
startMock = jest.fn(() => stopMock);
actual = getStartableStoppable(startMock);
});
it("does not start yet", () => {
expect(startMock).not.toHaveBeenCalled();
});
it("does not stop yet", () => {
expect(stopMock).not.toHaveBeenCalled();
});
it("when stopping before ever starting, throws", () => {
expect(() => {
actual.stop();
}).toThrow("Tried to stop something that has not started yet.");
});
describe("when started", () => {
beforeEach(() => {
actual.start();
});
it("starts", () => {
expect(startMock).toHaveBeenCalled();
});
it("does not stop yet", () => {
expect(stopMock).not.toHaveBeenCalled();
});
describe("when stopped", () => {
beforeEach(() => {
actual.stop();
});
it("stops", () => {
expect(stopMock).toHaveBeenCalled();
});
it("when stopped again, throws", () => {
expect(() => {
actual.stop();
}).toThrow("Tried to stop something that has already stopped.");
});
it("when started again, throws for restart being YAGNI with logical blind spots", () => {
expect(() => {
actual.start();
}).toThrow("Tried to restart something that has stopped.");
});
});
});
});

View File

@ -0,0 +1,37 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
export const getStartableStoppable = (
startAndGetStopCallback: () => () => void,
) => {
let dispose: () => void;
let stopped = false;
let started = false;
return {
start: () => {
if (started) {
throw new Error("Tried to restart something that has stopped.");
}
dispose = startAndGetStopCallback();
started = true;
},
stop: () => {
if (!started) {
throw new Error("Tried to stop something that has not started yet.");
}
if (stopped) {
throw new Error("Tried to stop something that has already stopped.");
}
dispose();
stopped = true;
},
};
};