import DeferredRunner from "../deferredRunner"

describe('Deferred runner', () => {
    it("should call enqueued methods after activating it", () => {
        const anyfunc = jest.fn()
        let mockLibrary = {
            anyfunc
        }

        const mockLibrarySpy = jest.spyOn(mockLibrary, 'anyfunc')

        const deferredRunner = new DeferredRunner()

        deferredRunner.execute('module', 'anyfunc', [1])
        deferredRunner.execute('module', 'anyfunc', [2])
        deferredRunner.execute('module', 'anyfunc', [3])
        deferredRunner.execute('module', 'anyfunc', [4])

        deferredRunner.activate({'module': mockLibrary})

        expect(mockLibrarySpy).toHaveBeenCalledTimes(4)
    })

    it("should call methods once it is activated", () => {
        const anyfunc = jest.fn()
        let mockLibrary = {
            anyfunc
        }

        const mockLibrarySpy = jest.spyOn(mockLibrary, 'anyfunc')

        const deferredRunner = new DeferredRunner()

        deferredRunner.execute('module', 'anyfunc', [1])
        deferredRunner.execute('module', 'anyfunc', [2])
        deferredRunner.execute('module', 'anyfunc', [3])
        deferredRunner.execute('module', 'anyfunc', [4])

        deferredRunner.activate({'module': mockLibrary})

        deferredRunner.execute('module', 'anyfunc', [5])

        expect(mockLibrarySpy).toHaveBeenCalledTimes(5)
    })

    it('should call a method after an error in a previous one', () => {
        const firstFunc = jest.fn()
        const secondFunc = jest.fn(() => {
            throw new Error()
        })
        const thirdFunc = jest.fn()

        const mockLibrary = {
            firstFunc,
            secondFunc,
            thirdFunc
        }

        const mockLibrarySpy = jest.spyOn(mockLibrary, 'thirdFunc')

        const deferredRunner = new DeferredRunner()

        deferredRunner.execute('module', 'firstFunc', [5])
        deferredRunner.execute('module', 'secondFunc', [5])
        deferredRunner.execute('module', 'thirdFunc', [5])

        deferredRunner.activate({'module': mockLibrary})

        expect(mockLibrarySpy).toBeCalled()
    })
})