api.test.js 2.18 KB
/**
 * http api 测试
 *
 * @author: jiangfeng<jeff.jiang@yoho.cn>
 * @date: 2016/05/17
 */
'use strict';

const test = require('ava');
const sign = require('../../library/sign');


const API = require('../../library/api').API;
const ServiceAPI = require('../../library/api').ServiceAPI;
const SearchAPI = require('../../library/api').SearchAPI;

const getUrl = 'operations/api/v6/category/getCategory';

test('api constructor test', (t) => {
    let api = new ServiceAPI();
    let api2 = new API();
    let api3 = new SearchAPI();

    t.true(api !== null);
    t.true(api2 !== null);
    t.true(api3 !== null);
});

test('api get test', t => {
    let api = new ServiceAPI();

    return api.get(getUrl, sign.apiSign({})).then(result => {
        if (result && result.code) {
            t.pass();
        } else {
            t.fail();
        }
    });
});

test('api get test, api return an error', t => {
    let api = new ServiceAPI();

    return api.get(getUrl + '/error', sign.apiSign({})).catch(err => {

        // 故意调用一个错误的接口
        if (err && err.code === 500) {
            t.pass();
        } else {
            t.fail();
        }
    });
});

test('api get use cache test', t => {
    let api = new ServiceAPI();

    return api.get(getUrl, sign.apiSign({}), true).then(result => {
        if (result && result.code) {
            t.pass();
        } else {
            t.fail();
        }
    });
});

test('api post test', t => {
    let api = new ServiceAPI();

    return api.post(getUrl, sign.apiSign({})).then(result => {
        if (result && result.code) {
            t.pass();
        } else {
            t.fail();
        }
    });
});

test('api multiple call test', (t) => {
    let api = new ServiceAPI();
    let multi = [api.get(getUrl, sign.apiSign({})), api.get(getUrl, sign.apiSign({}))];

    return api.all(multi).then(result => {
        if (result.length === 2) {
            t.pass();
        } else {
            t.fail();
        }
    });
});

test('api multiple fail call test', (t) => {
    let api = new ServiceAPI();

    return api.all(1).catch((e) => {
        if (e) {
            t.pass();
        } else {
            t.fail();
        }
    });
});