lundi 2 mai 2016

how do I test a Promise .then() block in Sinon / Karma / Mocha?

I want to write a test for an async React Redux function that looks like so:

export function requestItems(key, splat) {
    return (dispatch, getState) => {
        const firstReq = directLoader.loadArticle(splat); // returns a resolved Promise
        const secondReq = trendingLoader.loadArticles(key); // returns a resolved Promise

        Promise.all([firstReq, secondReq]).then(([direct, trending]) => {
            dispatch(addItems([direct, trending], key));
        });
    }
}

Here is what I have for a test so far:

it('should direct request if given a splat', () => {
    const res = { data: 'test' };
    const resolvedDirectPromise = Promise.resolve(res);
    const resolvedTrendingPromise = Promise.resolve({});

    // create stubs of the functions we're using
    sinon.stub(directLoader, 'loadArticle').returns(resolvedDirectPromise);
    sinon.stub(trendingLoader, 'loadArticles').returns(resolvedTrendingPromise);

    thunk = requestItems('aKey', 'aSplat');
    thunk(dispatchSpy, stateSpy);

    expect(directLoader.loadArticle.callCount).to.equal(1);
});

so a couple of issues...

  1. I expect the expect() to pass, however I get AssertionError: expected 0 to equal 1. Why does the function not execute?
  2. I have no idea how to test the contents of the .then() part of the function.. how do I do that?

Thanks in advanced for any help. :)

Aucun commentaire:

Enregistrer un commentaire