|
| 1 | + |
| 2 | +'use strict'; |
| 3 | + |
| 4 | +const request = require('supertest'); |
| 5 | +const assert = require('assert'); |
| 6 | +const Koa = require('../..'); |
| 7 | + |
| 8 | +describe('app.currentContext', () => { |
| 9 | + it('should throw error if AsyncLocalStorage not support', () => { |
| 10 | + if (require('async_hooks').AsyncLocalStorage) return; |
| 11 | + assert.throws(() => new Koa({ asyncLocalStorage: true }), |
| 12 | + /Requires node 12\.17\.0 or higher to enable asyncLocalStorage/); |
| 13 | + }); |
| 14 | + |
| 15 | + it('should get currentContext return context when asyncLocalStorage enable', async() => { |
| 16 | + if (!require('async_hooks').AsyncLocalStorage) return; |
| 17 | + |
| 18 | + const app = new Koa({ asyncLocalStorage: true }); |
| 19 | + |
| 20 | + app.use(async ctx => { |
| 21 | + assert(ctx === app.currentContext); |
| 22 | + await new Promise(resolve => { |
| 23 | + setTimeout(() => { |
| 24 | + assert(ctx === app.currentContext); |
| 25 | + resolve(); |
| 26 | + }, 1); |
| 27 | + }); |
| 28 | + await new Promise(resolve => { |
| 29 | + assert(ctx === app.currentContext); |
| 30 | + setImmediate(() => { |
| 31 | + assert(ctx === app.currentContext); |
| 32 | + resolve(); |
| 33 | + }); |
| 34 | + }); |
| 35 | + assert(ctx === app.currentContext); |
| 36 | + app.currentContext.body = 'ok'; |
| 37 | + }); |
| 38 | + |
| 39 | + const requestServer = async() => { |
| 40 | + assert(app.currentContext === undefined); |
| 41 | + await request(app.callback()).get('/').expect('ok'); |
| 42 | + assert(app.currentContext === undefined); |
| 43 | + }; |
| 44 | + |
| 45 | + await Promise.all([ |
| 46 | + requestServer(), |
| 47 | + requestServer(), |
| 48 | + requestServer(), |
| 49 | + requestServer(), |
| 50 | + requestServer() |
| 51 | + ]); |
| 52 | + }); |
| 53 | + |
| 54 | + it('should get currentContext return undefined when asyncLocalStorage disable', async() => { |
| 55 | + const app = new Koa(); |
| 56 | + |
| 57 | + app.use(async ctx => { |
| 58 | + assert(app.currentContext === undefined); |
| 59 | + ctx.body = 'ok'; |
| 60 | + }); |
| 61 | + |
| 62 | + await request(app.callback()).get('/').expect('ok'); |
| 63 | + }); |
| 64 | +}); |
0 commit comments