import asyncElementResizeHelper from 'bitbucket/internal/util/async-element-resize-helper';

QUnit.module('util-async-element-resize-helper', {
    beforeEach() {
        // I'm aware of the limits of stubbing rAF, but it's good enough for these tests!
        this.rAFStub = sinon.stub(window, 'requestAnimationFrame', cb => setTimeout(cb));
        this.clock = sinon.useFakeTimers();
        this.fixture = document.getElementById('qunit-fixture');

        this.el = document.createElement('div');
        this.el.style.width = '500px';
        this.el.style.height = '500px';
        this.fixture.appendChild(this.el);
    },
    afterEach() {
        this.rAFStub.restore();
        this.clock.restore();
    }
});

QUnit.test('callback only called once if element size does did not change', function (assert) {
    const callback = sinon.spy();
    asyncElementResizeHelper(this.el, callback);
    this.clock.tick(100);
    asyncElementResizeHelper(this.el, callback);
    this.clock.tick(100);

    sinon.assert.calledOnce(callback);
});

QUnit.test('callback called twice if element size changes', function (assert) {
    const callback = sinon.spy();
    asyncElementResizeHelper(this.el, callback);
    this.clock.tick(100);
    this.el.style.width = '501px';
    asyncElementResizeHelper(this.el, callback);
    this.clock.tick(100);

    sinon.assert.calledTwice(callback);
});

QUnit.test('error is thrown if null element passed', function (assert) {
   try {
       asyncElementResizeHelper(null, () => {});
       assert.fail('expected an error');
   } catch (ex) {
       assert.ok(ex);
   }
});