import configureMockStore from 'redux-mock-store';
import server from 'bitbucket/util/server';
import thunkMiddleware from 'bitbucket/internal/bbui/utils/thunk-middleware';
import loadRecentRepos from 'bitbucket/internal/feature/dashboard/action-creators/load-recent-repositories';
import { LOAD_REPOSITORIES, LOAD_REPOSITORIES_FAILURE, LOAD_REPOSITORIES_SUCCESS } from 'bitbucket/internal/feature/dashboard/actions';

QUnit.module('dashboard-load-recent-repositories', {
    beforeEach: function () {
        this.mockStore = configureMockStore([thunkMiddleware]);
        this.restStub = sinon.stub(server, 'rest');
    },
    afterEach: function () {
        this.restStub.restore();
    }
});

QUnit.test('it dispatches actions on success', function (assert) {
    const deferred = $.Deferred();
    deferred.resolve('payload');

    const expectedActions = [
        { type: LOAD_REPOSITORIES, meta: { repoType: 'recent' } },
        { type: LOAD_REPOSITORIES_SUCCESS, meta: { repoType: 'recent' }, payload: 'payload' },
    ];

    this.restStub.returns(deferred);
    const store = this.mockStore();
    store.dispatch(loadRecentRepos());

    const request = this.restStub.firstCall.args[0];
    assert.ok(request.url.indexOf('recent') !== -1);

    const actions = store.getActions();
    assert.deepEqual(actions, expectedActions);
});

QUnit.test('it dispatches actions on failure', function (assert) {
    const deferred = $.Deferred();
    deferred.reject('payload');

    const expectedActions = [
        { type: LOAD_REPOSITORIES, meta: { repoType: 'recent' } },
        { type: LOAD_REPOSITORIES_FAILURE, meta: { repoType: 'recent' }, payload: 'payload' },
    ];

    this.restStub.returns(deferred);
    const store = this.mockStore();
    store.dispatch(loadRecentRepos());
    const actions = store.getActions();
    assert.deepEqual(actions, expectedActions);
});