【问题标题】:How to test request value returned in a middleware如何测试中间件中返回的请求值
【发布时间】:2021-10-25 15:14:20
【问题描述】:

我是新手,我有类似的东西要测试。

function getProfit() {
  let profit = 0;

  ** some axios called where profit is updated form the returned value **

  return (req, res, next) => {
    req.properties = {
      profit,
    };

    next();
  };
}

module.exports = {
  getProfit,
};

我想测试这个函数的返回值。我尝试了类似的方法,但它不起作用:

const sinon = require('sinon');
const axios = require('axios');
const properties = require('../../middleware/properties');

describe('Properties Middleware', () => {
  let sandbox;
  beforeEach(() => {
    sandbox = sinon.createSandbox();
  });

  afterEach(() => {
    sandbox.restore();
  });

  it('should return the profit value in request', async () => {
    const profitMockData = { profit: 100 };

    sandbox.stub(axios, 'get').resolves({ data: 100 });

    const req = jest.fn()
    const res = { sendStatus: jest.fn() }
    const next = jest.fn();

    const response = await properties.getProfit(req, res, next);

    expect(response.req.properties.profit).toEqual(profitMockData.profit);

  });
});
 

这部分response.req.properties.profit是错误的,因为我不知道如何从req中获取值。

任何帮助将不胜感激。谢谢

【问题讨论】:

  • 也许我理解你的问题是错误的,但我觉得你正在寻找的答案在这里:stackoverflow.com/questions/65980172/…
  • 嗨@EtienneMartel,感谢您的评论。我看了看,但我的要简单得多。当我调试和评估response 变量时,我可以看到测试工作正常。只是不知道怎么取值

标签: javascript reactjs unit-testing testing jestjs


【解决方案1】:
const sinon = require('sinon');
const axios = require('axios');
const properties = require('../../middleware/properties');

describe('Properties Middleware', () => {
  let sandbox;
  beforeEach(() => {
    sandbox = sinon.createSandbox();
  });

  afterEach(() => {
    sandbox.restore();
  });

  it('should return the profit value in request', async () => {
    const profitMockData = { profit: 100 };

    sandbox.stub(axios, 'get').resolves({ data: 100 });

    const response = await properties.getProfit(req, res, next);

    const req = {};
    response(req, {}, () => {});

    expect(response.req.properties.profit).toEqual(profitMockData.profit);

  });
});

在同事的帮助下,我终于弄明白了。因此,首先,在对 get 部分进行存根后将其分配给所有函数,然后将其分配给 req、{}、() => {}。我们不需要 res 和 next,因为我们只关心 req ,这就是为什么我们也没有将它们作为变量。

【讨论】:

  • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
  • 1970-01-01
  • 2019-03-29
  • 2014-10-31
  • 1970-01-01
  • 2020-12-29
相关资源
最近更新 更多