【问题标题】:Unit Testing and Continuation-Local Storage单元测试和延续——本地存储
【发布时间】:2019-03-07 21:38:48
【问题描述】:

我想在我的 TypeScript 应用程序中利用 CLS(连续本地存储),这样我就可以在某个地方放置元数据(例如用户 ID、请求 ID)以用于各种用途(例如日志记录),而无需将数据传入每个方法调用。

我尝试同时使用cls-hookedasync-local-storage。但是,我无法从我的 Jest 单元测试中得到任何工作。

const als = require('async-local-storage');
als.enable();

// ... some code

describe('Authorization tests', () => {
  test('Cannot call without correct scope', () => {
    als.set('id', "123123123123");
    expect(() => service.registerApp(ctxt, app)).toThrowError(AuthorizationError.NOT_AUTHORIZED);
  });
});

以上设置基准id没有失败。

export function authorize(requiredPermissions: string[]) {
    return (target: any, name: any, descriptor: any) => {
        const protectedFunction = descriptor.value;
        const als = require('async-local-storage');
        console.log(`>>>>>>>>>My ID ${als.get('id')}`);

        // ... some code
    }
}

但是上面的代码只是简单的输出:

>>>>>>>>>My ID null

我正在尝试的可能吗?提前致谢。

【问题讨论】:

    标签: javascript node.js typescript jestjs


    【解决方案1】:

    由于 Jest 似乎不支持 localStorage,因此您需要对其进行模拟。

    我建议为此使用诸如https://www.npmjs.com/package/jest-localstorage-mock 之类的库,否则您必须自己实现它。

    您需要将该库添加到您的 devDependencies 并将其作为一个 jest setupFile 添加到 package.json 中:

    {
      "jest": {
        "setupFiles": ["jest-localstorage-mock"]
      }
    }
    

    在那之后你的测试应该通过了。

    【讨论】:

      【解决方案2】:

      我能够在不需要 jest-localstorage-mock 依赖项的情况下解决我的问题。简而言之,我的get(...) 调用试图在启用异步挂钩之前读取存储,这是根据the documentation 的要求。此外,我的get(...) 电话试图过早地阅读商店;因为我试图在装饰器中执行此操作,所以我需要将 get 调用移动到 descriptor.value,这实际上是在运行时执行的。

      我更新的生产代码现在包含enable() 调用,get(...) 调用在正确的位置,一切都很好:

      const als = require('async-local-storage'); // pulled up to top of file
      als.enable(); // added
      
      export function authorize(requiredPermissions: string[]) {
          return (target: any, name: any, descriptor: any) => {
              const protectedFunction = descriptor.value;
      
              descriptor.value = function() {
                  console.log(`>>>>>>>>>My ID ${als.get('id')}`); // moved into function
                  // ... some code
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-10
        • 1970-01-01
        • 2019-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多