import createMutationsSharer from "./vuexSharedMutations";

describe("Vuex shared mutations", () => {
    it("should throw an error if predicate function is not supplied", () => {
        expect(() => {
            createMutationsSharer();
        }).toThrowError(Error);
    });
    it("should accept array as predicate", () => {
        expect(() => {
            createMutationsSharer({
                predicate: ["m-1"],
            });
        }).not.toThrowError(Error);
    });
    it("should accept function as predicate", () => {
        expect(() => {
            createMutationsSharer({
                predicate: jest.fn(),
            });
        }).not.toThrowError(Error);
    });
    it("should share relevant mutation", () => {
        let capturedHandler;
        const fakeStrategy = {
            share: jest.fn(),
            addEventListener: jest.fn(),
        };

        const fakeStore = {
            subscribe(fn) {
                capturedHandler = fn;
            },
        };

        createMutationsSharer({
            predicate: ["m-1"],
            strategy: fakeStrategy,
        })(fakeStore);

        return capturedHandler({ type: "m-1", payload: "lol" }).then(() => {
            expect(fakeStrategy.share).toHaveBeenCalled();
        });
    });
    it("should not share irrelevant mutation", () => {
        let capturedHandler;
        const fakeStrategy = {
            share: jest.fn(),
            addEventListener: jest.fn(),
        };

        const fakeStore = {
            subscribe(fn) {
                capturedHandler = fn;
            },
        };

        createMutationsSharer({
            predicate: ["m-1"],
            strategy: fakeStrategy,
        })(fakeStore);
        return capturedHandler({ type: "m-2", payload: "lol" }).then(() => {
            expect(fakeStrategy.share).not.toHaveBeenCalled();
        });
    });
    it("should respect predicate function when sharing mutation", () => {
        let capturedHandler;
        const fakeStrategy = {
            share: jest.fn(),
            addEventListener: jest.fn(),
        };

        const fakeStore = {
            subscribe(fn) {
                capturedHandler = fn;
            },
        };

        createMutationsSharer({
            predicate: ({ type }) => ["m-1"].indexOf(type) !== -1,
            strategy: fakeStrategy,
        })(fakeStore);

        return capturedHandler({ type: "m-1", payload: "lol" }).then(() => {
            expect(fakeStrategy.share).toHaveBeenCalled();
        });
    });
});
