簡體   English   中英

對具有回調的 function 的 function 進行單元測試(請求模塊)

[英]Unit test a function which has a function with callback (request module)

我正在我的 NodeJS 項目中進行測試,我有以下 function 我想進行單元測試:

function myRequest(targetUrl, reqBody) {
  return new Promise((resolve, reject) => {
    request.post(targetUrl, { json: reqBody }, (error, response, body) => {
      if (!error && response.statusCode === 200) {
        resolve(body.transferId);
      } else {
        reject(error || body.description || body);
      }
    });
  });
}

我正在使用摩卡和西農。 如何測試這個 function?

首先,我使用自己的模擬請求模塊對成功場景進行了測試。 現在,我想做錯誤場景,這可能是 function 后出現錯誤。 我怎么能在不更改或制作新的請求模擬(返回錯誤)的情況下做到這一點? 有可能嗎?

這是單元測試解決方案,您應該使用sinon.stub

例如index.ts

import request from 'request';

export function myRequest(targetUrl, reqBody) {
  return new Promise((resolve, reject) => {
    request.post(targetUrl, { json: reqBody }, (error, response, body) => {
      if (!error && response.statusCode === 200) {
        resolve(body.transferId);
      } else {
        reject(error || body.description || body);
      }
    });
  });
}

index.spec.ts

import { myRequest } from '.';
import chai from 'chai';
import sinon from 'sinon';
import chaiAsPromised from 'chai-as-promised';
import request from 'request';
chai.use(chaiAsPromised);

const { expect } = chai;

describe('myRequest', () => {
  it('should request success', async done => {
    // @ts-ignore
    const stub = sinon.stub(request, 'post').callsFake((uri, options, callback) => {
      const mResponse = { statusCode: 200 };
      const mBody = { transferId: 1 };
      callback(null, mResponse, mBody);
      done();
    });
    const actualValue = await myRequest('url', {});
    // @ts-ignore
    stub.calledOnceWith('url', { json: {} });
    expect(actualValue).to.eq(1);
    stub.restore();
  });

  it('should throw error use request error', async done => {
    const mError = new Error('Internal server error');
    const mResponse = { statusCode: 500 };
    // @ts-ignore
    const stub = sinon.stub(request, 'post').callsFake((uri, options, callback) => {
      callback(mError, mResponse, null);
      done();
    });
    await expect(myRequest('url', {})).to.be.rejectedWith(mError);
    // @ts-ignore
    stub.calledOnceWith('url', { json: {} });
    stub.restore();
  });

  it('should throw error use body.description as error message', async done => {
    const mResponse = { statusCode: 500 };
    const mBody = { description: 'some error' };
    // @ts-ignore
    const stub = sinon.stub(request, 'post').callsFake((uri, options, callback) => {
      callback(null, mResponse, mBody);
      done();
    });
    await expect(myRequest('url', {})).to.be.rejectedWith(mBody.description);
    // @ts-ignore
    stub.calledOnceWith('url', { json: {} });
    stub.restore();
  });

  it('should throw error use body as error message', async done => {
    const mResponse = { statusCode: 500 };
    const mBody = 'some error';
    // @ts-ignore
    const stub = sinon.stub(request, 'post').callsFake((uri, options, callback) => {
      callback(null, mResponse, mBody);
      done();
    });
    await expect(myRequest('url', {})).to.be.rejectedWith(mBody);
    // @ts-ignore
    stub.calledOnceWith('url', { json: {} });
    stub.restore();
  });
});

覆蓋率 100% 的單元測試結果:

  myRequest
    ✓ should request success
    ✓ should throw error use request error
    ✓ should throw error use body.description as error message
    ✓ should throw error use body as error message


  4 passing (13ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |      100 |      100 |      100 |      100 |                   |
 index.spec.ts |      100 |      100 |      100 |      100 |                   |
 index.ts      |      100 |      100 |      100 |      100 |                   |
---------------|----------|----------|----------|----------|-------------------|

源碼: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/58822996

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM