nodejs -使用sinon来存根响应

wdebmtf2  于 2023-05-22  发布在  Node.js
关注(0)|答案(1)|浏览(120)

下面是nodejs代码。我正在尝试为module.exports.handle编写错误场景的单元测试。我所要做的就是模拟processData函数,使其返回错误。

module.exports.handle = async (event) => {
  const { body } = event;

    try {
      const response = await processData(body);
      if (response)
      {
         return { 201 };
      }
    catch (error) {
      return {
        500
      };
    }
  } 
};

async function processData() {
  try {
    const response = await externalServiceCall();
    return response;
  } catch (error) {
    console.error('error');
    throw error;
  }
}
dldeef67

dldeef671#

首先,你需要安装Mocha、Sinon和Chai作为开发依赖:

npm install --save-dev mocha sinon chai

创建测试文件,例如yourModule.test.js。在这个文件中,您将导入所需的依赖项,创建测试,并使用Sinon来存根响应。
下面是一个基于您的问题中提供的代码的示例:

const sinon = require('sinon');
const { handle, processData } = require('./yourModule'); // Update with the actual file name of your module
const { expect } = require('chai');

describe('handle function tests', () => {
  afterEach(() => {
    sinon.restore();
  });

  it('should return a 500 status when processData returns an error', async () => {
    // Stub processData function to return an error
    const processDataStub = sinon.stub(processData, 'processData');
    processDataStub.rejects(new Error('An error occurred'));

    // Sample event data
    const event = {
      body: {
        data: 'Sample data'
      }
    };

    const result = await handle(event);

    expect(result).to.deep.equal({ 500 });

    sinon.assert.calledOnce(processDataStub);
  });
});

相关问题