【问题标题】:Stubbing function with jest to test Internal error用笑话测试内部错误的存根函数
【发布时间】:2021-08-13 06:05:21
【问题描述】:

我正在尝试使用 jest 测试控制器功能,并且我想测试所有三个状态返回

const messagesSender = async (req, res) => {
  try {
    const { message } = req.body;
    if (!message) {
      return res.status(400).send({ message: 'Message cannot be null' });
    }
    return res.status(200).send(message);
  } catch (error) {
    return res.status(500).json({ error: 'Internal Error' });
  }
};

module.exports = { messagesSender };

测试文件:

const messages = require('../controller/messagesController');

describe('Testing Messages Controller', () => {

  it('should return internal error', async () => {
    const req = {
      body: {
        message: 'testing',
      },
    };
    const res = {
      send: jest.fn(),
      status: jest.fn(() => res),
    };
    const messageResponse = await messages.messagesSender(req, res);
    messageResponse.mockImplementation(() => {
      throw new Error('User not found');
    });
    expect(res.status).toBeCalledWith(500);
  });
});

但我收到错误消息:

TypeError: Cannot read property 'mockImplementation' of undefined

我该如何解决这个问题并测试 500 结果?

【问题讨论】:

    标签: node.js testing jestjs


    【解决方案1】:
      it('should return internal error', async () => {
        const req = {
          body: {
            message: 'testing',
          },
        };
        const res = {
          send: jest.fn().mockImplementation(() => {
            throw new Error('User not found');
          }),
          status: jest.fn(() => res),
        };
        await messages.messagesSender(req, res);
        expect(res.status.mock.calls[1][0]).toBe(500);
      });
    

    在您的情况下,send 函数不返回任何内容并导致此问题。在这种情况下,status 方法已经被调用了两次,所以你需要检查第二次调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 2020-06-24
      • 1970-01-01
      • 2018-08-09
      • 2019-09-06
      相关资源
      最近更新 更多