【问题标题】:How to send a signedCookie in Jest test如何在 Jest 测试中发送签名的 Cookie
【发布时间】:2023-01-28 05:16:45
【问题描述】:

我正在我的 Node.js/express 应用程序中编写 API 测试,我需要向不同的 API 发出请求。路由器请求接受一个签名的 cookie,以将 cookie 所有者添加为已发布事物的所有者,或识别用户/所有者。但是我显然无法登录到服务器来获取cookie。

我四处搜索,但没有发现任何与我相关的问题,所以有人知道如何在 Jest 测试中制作/模拟签名的 cookie 吗?

【问题讨论】:

    标签: node.js express cookies jestjs


    【解决方案1】:

    cookie-parser 库在底层使用cookie-signature 库。我假设您有权访问加密密钥或 cookie 秘密(在 .env 或任何地方)。没有它,您将无法签署您的 cookie。

    我正在使用 supertest 进行请求。

    import request from 'supertest';
    import { unsign } from 'cookie-signature';
    // If your key comes from .env
    import dotenv from 'dotenv';
    dotenv.config();
    
    const baseURL = 'http://localhost:3000';
    const key = process.env.COOKIE_SECRET; // Set your key here. Mine comes from .env
    
    describe('My super awesome test group', () => {
      it('test some stuff', async () => {
        const res = await request(app)
            .get('/your-endpoint')
            .set('Cookie', `myCookie=s:${sign('my value', key)}`);
        expect(res.status).toBe(200);
        // Do other assertions
      });
    });
    

    希望有所帮助:)

    【讨论】:

    • 对于 JSON cookie,请确保在签名前进行字符串化。 sign 方法只接受一个字符串参数。然后将“s:”前缀更改为“j:”就可以了。
    猜你喜欢
    • 2011-07-03
    • 2019-01-14
    • 1970-01-01
    • 2020-03-27
    • 2017-01-04
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多