All files / test/interface-proxy base_test.js

99.57% Statements 234/235
100% Branches 14/14
98.08% Functions 102/104
99.57% Lines 230/231

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583  1x       1x                                         1x           1x 1x                       1x                         1x 1x                                                                             1x                                                                                                                       1x   1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x     1x   1x     1x 1x 1x 1x       1x 1x 1x 1x       1x 1x   1x         1x 1x 1x 1x       1x 1x     1x 1x       1x 1x 1x 1x 1x       1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x       1x 1x 1x 1x       1x 1x 1x 1x       1x 1x 1x 1x       1x 1x 1x 1x 1x       1x 1x 1x 1x       1x 1x 1x 1x       1x 1x 1x 1x       1x 1x 1x 1x       1x 1x     3x 3x 3x 1x       1x 1x   1x 1x   1x 1x       1x 1x     2x 2x 1x 1x       1x 1x   1x 1x       1x 1x   1x 1x             1x 1x 1x 1x 1x 1x         1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x 1x 1x 1x 1x         1x 1x 1x 1x     1x 1x 1x 1x 1x     1x 2x   1x 1x 1x   1x         1x 1x 1x 1x       1x 1x           4x 1x       1x 1x         3x 1x       1x 1x         1x 1x 1x 1x       1x 1x         1x         1x 1x 1x 1x       1x 1x     1x 1x 1x     1x 1x       1x 1x 1x 1x       1x 1x 1x 1x                     1x 1x 1x 1x 1x 1x       1x 1x         1x 1x       1x 1x 1x     4x 2x   2x   4x 1x 1x 1x       1x 1x   1x     1x   1x   1x       1x 1x         1x 1x              
// import {InterfaceProxy} from '../../src/index.js';
import InterfaceProxy from '../../packages/interface';
 
describe("The InterfaceProxy requests", () => {
 
    const iProxy = new InterfaceProxy({
        // json/user
        jsonRequest: {
            pathname: '/api/json/user',
        },
        user: {
            pathname: '/api/json/user',
            params: {
                id: null,
                name: null,
                job: 'jobless',
                race: 'human',
            }
        },
        userOrigin: {
            mixins: 'user',
            origin: 'http://127.0.0.1:15678',
        },
        userWithTokenHeader: {
            mixins: 'user',
            beforeSend(xhr) {
                xhr.setRequestHeader('x-token', '0001');
            },
        },
        userIntroduction: {
            mixins: 'user',
            dataFilter: function (data) {
                data.query.introduction = `${data.query.name}-${data.query.job}`;
                return data;
            }
        },
        userWithTimestamp: {
            mixins: 'user',
            params: {
                id: String,
                name: {
                    type: String,
                    default: 'wdzxc',
                },
                timestamp() {
                    return +new Date();
                },
            }
        },
        postMan: {
            mixins: 'user',
            params: {
                job: 'postman',
            }
        },
        superUser: {
            mixins: 'user',
            paramsFilter(params) {
                params.job = 'super-' + params.job;
                return params;
            },
        },
        postmanIntroduction: {
            mixins: ['userIntroduction', 'postMan', {
                headers: {
                    'x-mixes': 'milk',
                }
            }],
        },
        userName: {
            mixins: 'user',
            dataPath: 'query.name',
        },
 
        // 基础测试
        jsonpSuccess: {
            pathname: '/api/jsonp/success',
            dataType: 'jsonp',
            jsonp: 'callback',
        },
        jsonpError: {
            pathname: '/api/jsonp/error',
            dataType: 'jsonp',
            jsonp: 'callback',
        },
        jsonSuccess: {
            url: '/api/json/success',
        },
        jsonFail: {
            pathname: '/api/json/fail',
        },
        postTest: {
            pathname: '/api/post',
            type: 'post',
        },
        jsonFailAsSuccess: {
            pathname: '/api/json/fail',
            successHandler(res) {
                return {
                    success: true,
                    data: res,
                }
            },
        },
        notFound: {
            pathname: '/api/404',
        },
        notFoundJsonp: {
            pathname: '/api/404',
            dataType: 'jsonp',
            jsonp: 'callback',
        },
        multiResponseHtml: {
            pathname: '/api/multiResponse',
            dataType: 'html',
        },
        multiResponseText: {
            pathname: '/api/multiResponse',
            dataType: 'text',
        },
        index: {
            pathname: '/api/json/index',
            params: {
                index: 0,
                delay: null,
            },
            queue: true,
        },
        indexMerge: {
            pathname: '/api/json/index',
            params: {
                index: 0,
                delay: null,
            },
            merge: true,
        },
        indexSingle: {
            pathname: '/api/json/index',
            params: {
                index: 0,
                delay: null,
            },
            single: true,
        },
        indexValidTime: {
            mixins: ['index'],
            validTime: 0.5,
        },
        pathParams: {
            pathname: '/api/pathParams/:id',
            validTime: 1,
        },
    }, [{
        headers: {
            'X-Requested-With': 'interface-proxy',
        },
    }]);
    // clear local storage
    localStorage.clear();
 
    it("is defined", () => {
        expect(InterfaceProxy).toBeDefined();
    });
    // 基础配置信息 & 功能
    it("can generate request method with base config and call callback with args after request success", (done) => {
        iProxy.user().then((data, response) => {
            expect(response.success).toBeTruthy();
            expect(response.data).toEqual(data);
            expect(data.method).toBe('GET');
            expect(data.baseUrl).toBe('/api/json/user');
            expect(data.query.job).toBe('jobless');
            expect(data.query.race).toBe('human');
            done();
        });
    });
    // method.url
    it("should supply url access property", (done) => {
        expect(iProxy.user.url).toBe('/api/json/user');
        done();
    });
    // method.buildUrl
    it("should supply url access property", (done) => {
        // TODO 为每个接口方法提供buildUrl方法,返回根据参数构造后的URL
        done();
    });
    // JSON success then
    it("with default json pattern should resolve {success:true,...} as success and extract data", (done) => {
        iProxy.jsonSuccess().then(data => {
            expect(data).toEqual({name: 'wdzxc'});
            done();
        });
    });
    // JSON error catch
    it("with default json pattern should resolve {success:false,...} as error and extract error msg", (done) => {
        iProxy.jsonFail().catch(msg => {
            expect(msg).toBe('server error');
            done();
        });
    });
    // JSON finally
    it("always call finally after catch & then ", (done) => {
        iProxy.jsonFail().catch(msg => {
        }).finally(() => {
            done();
        });
    });
 
    // 成功回调
    it("should call success callback when response status is success", (done) => {
        iProxy.jsonSuccess({a: 11}, data => {
            expect(data).toEqual({name: 'wdzxc'});
            done();
        });
    });
    // 失败回调
    it("should call error callback when response status is error", (done) => {
        iProxy.jsonFail(() => {
            // placeholder for success callback
        }, msg => {
            expect(msg).toBe('server error');
            done();
        });
    });
    // params 参数自动匹配
    it("should extract params according to config.param", (done) => {
        iProxy.user('999', 'wdzxc').then(data => {
            expect(data.query.id).toBe('999');
            expect(data.query.name).toBe('wdzxc');
            done();
        });
    });
    // params 参数默认值
    it("with params config should regard as default value to query params", (done) => {
        iProxy.user().then(data => {
            expect(data.query.race).toBe('human');
            expect(data.query.job).toBe('jobless');
            done();
        });
    });
    // params 参数默认值覆盖
    it("with params config should be cover by request query params", (done) => {
        iProxy.user({id: '999', job: 'postman'}).then(data => {
            expect(data.query.id).toBe('999');
            expect(data.query.race).toBe('human');
            expect(data.query.job).toBe('postman');
            done();
        });
    });
    // 请求 dataType为 html
    it("should support dataType as html", (done) => {
        iProxy.multiResponseHtml().then(data => {
            expect(data).toBe("<p>hey</p>");
            done();
        });
    });
    // 请求 dataType为 text
    it("should support dataType as text", (done) => {
        iProxy.multiResponseText().then(data => {
            expect(data).toBe('hey');
            done();
        });
    });
    // 配置项 混入模式
    it("should support mixins config", (done) => {
        iProxy.postMan().then(data => {
            expect(data.query.job).toEqual('postman');
            done();
        });
    });
    // 配置项 多重混入 & dataFilter
    it("should support complex mixins & dataFilter", (done) => {
        iProxy.postmanIntroduction({name: 'wdzxc'}).then(data => {
            expect(data.query.introduction).toEqual('wdzxc-postman');
            expect(data.headers['x-mixes']).toEqual('milk');
            done();
        });
    });
    // 配置项 paramsFilter
    it("should support config paramsFilter", (done) => {
        iProxy.superUser({job: 'police'}).then(data => {
            expect(data.query.job).toEqual('super-police');
            done();
        });
    });
    // 配置项 dataPath
    it("should auto extract response data according to dataPath config", (done) => {
        iProxy.userName({name: 'wdzxc'}).then(data => {
            expect(data).toEqual('wdzxc');
            done();
        });
    });
    // 配置项 origin
    it("should replace request origin according to origin config", (done) => {
        iProxy.userOrigin().then(data => {
            expect(data.hostname).toEqual('127.0.0.1');
            done();
        });
    });
    // 配置项 beforeSend
    it("should support beforeSend hook", (done) => {
        iProxy.userWithTokenHeader().then(data => {
            expect(data.headers['x-token']).toEqual('0001');
            done();
        });
    });
    // 配置项 queue 排队请求
    it("should orderly call callback as request sequence when queue config set true", (done) => {
        let returns = [];
 
        function archive(data) {
            returns.push(data);
            if (returns.length === 3) {
                expect(returns.map(value => value.index).join('-')).toEqual('1-2-3');
                done();
            }
        }
 
        iProxy.index({index: 1, delay: 1000}).then(data => {
            archive(data);
        });
        iProxy.index({index: 2, delay: 1}).then(data => {
            archive(data);
        });
        iProxy.index({index: 3, delay: 500, error: true}).catch((msg, data) => {
            archive(data.data);
        });
    });
    // 配置项 merge 合并相同请求
    it("should merge same query request when merge config set true", (done) => {
        let returns = [];
 
        function archive(data) {
            returns.push(data);
            if (returns.length === 2) {
                expect(returns[0]['counter'] === returns[1]['counter']).toBeTruthy();
                done();
            }
        }
 
        iProxy.indexMerge({index: 1, delay: 300}).then(data => {
            archive(data);
        });
        iProxy.indexMerge({index: 1, delay: 300}).then(data => {
            archive(data);
        });
    });
    // 配置项 single 同一个接口的请求仅响应最后一个
    it("should only response callback last request when config set true", (done) => {
        let returns = [];
 
        iProxy.indexSingle({index: 1, delay: 100}).then(data => {
            returns.push(data);
        });
        // iProxy.indexSingle({index: 2, delay: 500}).then(data => {
        //     console.log(data);
        //     expect(returns.length).toBeLessThan(1);
        //     done();
        // });
        setTimeout(() => {
            console.log(returns);
            iProxy.indexSingle({index: 2, delay: 500}).then(data => {
                console.log(returns);
                expect(returns.length).toBeLessThan(1);
                done();
            });
        }, 1);
    });
 
    it("should support hook successHandler to custom response state check", (done) => {
        iProxy.jsonFailAsSuccess().then(data => {
            expect(data).toEqual({success: false, msg: 'server error'});
            done();
        });
    });
 
    it("should support config validTime", (done) => {
        let cacheData = null;
        let query = {index: 9999, delay: 500};
        iProxy.indexValidTime(query).then(data => {
            cacheData = data;
            let newData = null;
            iProxy.indexValidTime(query).then((data) => {
                newData = data;
            });
            setTimeout(() => {
                expect(newData).toEqual(cacheData);
            }, 50);
            setTimeout(() => {
                iProxy.indexValidTime(query).then((data) => {
                    newData = data;
                    expect(data.counter === cacheData.counter).toBeFalsy();
                    done();
                });
            }, 550);
        });
    });
    it("should support jsonp", (done) => {
        iProxy.jsonpSuccess().then(data => {
            expect(data.callback).toBeTruthy();
            done();
        });
    });
    it("should move query params to body when request method is post", (done) => {
        iProxy.postTest({data: 666}).then((data, response) => {
            expect(data).toEqual({data: 666});
            expect(response).toEqual({success: true, data: {data: 666}});
            done();
        });
    });
    it("can work with es7 async function", (done) => {
        (async function () {
            async function test() {
                try {
                    var successData = await iProxy.jsonSuccess();
                    var failData = await iProxy.jsonFail();
                } catch (e) {
                    return {successData, failData}
                }
                return {successData, failData};
            }
 
            let {successData, failData} = await test();
            expect(successData).toBeDefined();
            expect(failData).toBeUndefined();
            done();
        })();
    });
 
    it("should support multiple methods [get,delete,head,option]", (done) => {
        Promise.all([
            iProxy.user.get(),
            iProxy.user.delete(),
            iProxy.user.head(),
            iProxy.user.options(),
        ]).then(data => {
            expect(data.map(res => res && res.method)).toEqual(['GET', 'DELETE', null, null]);
            done();
        });
    });
 
    it("should support multiple methods [post,put,patch]", (done) => {
        Promise.all([
            iProxy.user.post(),
            iProxy.user.put(),
            iProxy.user.patch(''),
        ]).then(data => {
            expect(data.map(res => res && res.method)).toEqual(['POST', 'PUT', 'PATCH']);
            done();
        });
    });
 
    it("should support multiple methods post data", (done) => {
        let user = {
            name: 'lina',
            job: 'sorceress',
            race: 'human',
        };
        iProxy.user.post(user).then(data => {
            expect(data.method).toBe('POST');
            expect(data.body).toEqual(user);
            done();
        });
    });
 
    it("should support multiple methods config", (done) => {
        let user = {
            name: 'lina',
            job: 'sorceress',
            race: 'human',
        };
        iProxy.user.post(user, {
            headers: {
                'x-token': '777',
            },
        }).then(data => {
            expect(data.method).toBe('POST');
            expect(data.body).toEqual(user);
            expect(data.headers['x-token']).toBe('777');
            done();
        });
    });
 
    it("should support loadingSwitch config", (done) => {
        let testSwitch = {
            state: false,
        };
        iProxy.index({delay: 200}).loadingSwitch(testSwitch, 'state').finally(() => {
            expect(testSwitch.state).toBeFalsy();
            done();
        });
        // loadingSwitch trigger progress will async start
        setTimeout(() => {
            expect(testSwitch.state).toBeTruthy();
        }, 10);
    });
 
    it("should support error status 404", (done) => {
        iProxy.notFound().catch(err => {
            expect(err).toBe('Request failed with status code 404');
            done();
        });
    });
 
    it("should support catch jsonp status error", (done) => {
        iProxy.notFoundJsonp().catch(err => {
            expect(err).toBe('Jsonp request error');
            done();
        });
    });
 
    // it("should support catch jsonp format error", (done) => {
    //     iProxy.jsonpError().catch(err => {
    //         expect(err).toBe('Jsonp response illegal');
    //         done();
    //     });
    // });
 
    it("should support params with Function & Types & {default:...} properties", (done) => {
        iProxy.userWithTimestamp().then(data => {
            expect(data.query.id).toBeUndefined();
            expect(data.query.name).toBe('wdzxc');
            expect(data.query.timestamp + 10000).toBeGreaterThan(+new Date());
            done();
        })
    });
 
    it("should support config pathParams", (done) => {
        iProxy.pathParams.get(null, {
            pathParams: {
                id: 888,
            }
        }).then(data => {
            expect(data.baseUrl).toBe('/api/pathParams/888');
            done();
        })
    });
 
    it("should call promise callback after params callback", (done) => {
        let returns = [];
        let errReturns = [];
 
        function archive(data, type) {
            if (type) {
                errReturns.push(data);
            } else {
                returns.push(data);
            }
            if (returns.length === 2 && errReturns.length === 2) {
                expect(returns[0]).toEqual(returns[1]);
                expect(errReturns[0]).toEqual(errReturns[1]);
                done();
            }
        }
 
        iProxy.jsonSuccess(data => {
            archive(data);
        }).then(data => {
            archive(data);
        });
 
        iProxy.jsonFail(() => {
        }, msg => {
            archive(msg, 'error');
        }).catch(msg => {
            archive(msg, 'error');
        });
    });
 
    it("should post....", (done) => {
        iProxy.jsonRequest.post('wdzxc', {
            headers: {
                "Content-Type": "text/plain",
            }
        }).then(data => {
            expect(data.body).toEqual("wdzxc");
            done();
        });
    });
 
    // TODO
    // 一个BUG 在 single 的情况下,用同一个方法异步快速连续发送两次请求 会出现一次回调都没有的情况
    // single: true,
});