单元测试在javascript中使用冰棒的异步网络调用

时间:2017-06-02 02:01:44

标签: javascript unit-testing asynchronous promise mocha

我正在编写一个简单的javascript sdk,我正在围绕popsicle请求对象创建一个包装器并编写一个fetch方法。它看起来像这样。

import request from 'popsicle';

export default function fetchPosts(postsRequest) {
    // some validations
    const url = 'api/posts';
    const postsRequestData = Object.assign({}, balboaRequest, {url});
    if (!authPreflightPromise) {
        authPreflightPromise = new Promise((resolve, reject) => {
            // Disable auth preflight if configured to do so.
            if (!postsRequest.enableAuthPreflight) {
                resolve();
            }

            const authPreflightUrl = 'http://somedomain.com/auth?state=hasArgs';
            const authPreflightRequestData = Object.assign({}, {method: 'POST'}, {url: authPreflightUrl});
            request(authPreflightRequestData)
                .then(() => {
                    resolve();
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    return authPreflightPromise.then(() => {
        return request(postsRequestData);
    });
}

现在我想进行单元测试而不进行实际的网络调用。我了解到冰棒正在使用fetch api,所以我想到使用fetch-mock库并编写测试,如他们的示例中所示,但它没有捕获网络调用,并且由于网络调用失败,我的单元测试仍然失败。

不知道我哪里出错了。

import fetchPosts from '../../src/fetchPosts.js';
const fetchMock = require('fetch-mock');

describe('tests for fetch posts ', () => {

    it('should return the posts returned by the api for valid requests', () => {

        // Mock the fetch() global to always return the same value for GET
        fetchMock.get('*', {foo: 'bar'});

        var fetchPostsPromise = fetchPosts(createValidRequest(username));

        return fetchPostsPromise.then((data) => {
            console.log(data);
            expect(fetchMock.called()).equal(true);
            fetchMock.restore();
        }).catch((error) => {
            console.log(error);
            fetchMock.restore();
        });
    });

});

1 个答案:

答案 0 :(得分:0)

首先,在fetchPosts中,我没有看到authPreflightPromise的定义

然后如果你想测试异步函数,你应该使用done callback,否则你会得到一个timeout error;

it('should return the posts returned by the api for valid requests', (done) => {

    fetchMock.get('*', {foo: 'bar'});

    var fetchPostsPromise = fetchPosts(createValidRequest(username));

    return fetchPostsPromise.then((data) => {
        console.log(data);
        expect(myMock.called()).equal(true);
        fetchMock.restore();
        // tell mocha this test has finished
        done();
    }).catch((error) => {
        console.log(error);
        fetchMock.restore();
        done();
    });
// don't forget to set timeout, or you may get a timeout error
}).timeout(10000)