【问题标题】:Mocking in jest and express开玩笑和表达
【发布时间】:2020-05-24 02:03:42
【问题描述】:

我在 Express 路由中有一些代码可以与 AWS Cognito 对话,但我无法弄清楚如何在测试中模拟它。

cognitoExpress.validate(accessTokenFromClient, (err, response) => {
    if (err) return res.status(401).json({ error: err });

    res.json({ data: `Hello ${response.username}!` });
  });

然后在我的测试中我想说 cognitoExpress.validate 应该被调用一次并返回 {username: 'test user'} 以便它不会访问网络并且实际上不会调用 AWS Cognito

it('It should returns 200 with a valid token', async done => {
    const { cognitoExpress } = require('../helpers/cognitoExpress');

    // I have tried
    jest.mock('../helpers/cognitoExpress');
    // and this
    jest.mock('../helpers/cognitoExpress', () => ({
      validate: jest.fn()
    }));

    const token = 'sfsfdsfsdfsd';
    const response = await request.get('/').set('Authorization', token);
    expect(cognitoExpress.validate).toHaveBeenCalledWith(token);
    expect(response.body).toEqual({ data: 'Hello test user' });
    done();
  });

提前谢谢....

【问题讨论】:

    标签: node.js express testing mocking jestjs


    【解决方案1】:

    使用要使用的模拟函数创建文件../helpers/__mocks__/cognitoExpress.js。必须调用文件夹__mocks__。您可以修改函数并返回您想要的任何数据。

    示例

    module.exports = { 
        validate: () => { username: 'test user' }
    }
    

    现在您可以使用jest.mock('../helpers/cognitoExpress'),但我建议您将其放在某个全局或测试设置文件中,而不是单独的测试中。

    Jest Manual Mocks

    【讨论】:

      【解决方案2】:
      let spyInstance = undefined;
      
      beforeAll(() => {
        spyInstance = jest.spyOn(cognitoExpress.prototype, "validate").mockImplementation(() => {
          // Replace the body of 'validate' here, ensure it sets
          // response body to {username: 'test user'} without calling AWS 
          ...
        });
      });
      
      afterAll(() => {
        expect(spyInstance).toBeDefined();
        expect(spyInstance).toHaveBeenCalledTimes(1);
        jest.restoreAllMocks();
      });
      
      
      it("It should call mocked cognitoExpress.validate once", async done => {
       ...
      });
      
      

      我的项目中有一个类似且有效的test。而不是 cognitoExpress.validate 它模拟和测试 SampleModel.getData

      【讨论】:

        猜你喜欢
        • 2022-06-23
        • 1970-01-01
        • 2020-02-24
        • 2021-01-10
        • 2021-08-14
        • 2020-11-22
        • 1970-01-01
        • 1970-01-01
        • 2022-08-07
        相关资源
        最近更新 更多