繁体   English   中英

Sinon JS 存根 HTTP 请求

[英]Sinon JS Stub HTTP Request

我需要为端点创建一个单元测试,该端点将向某个 API 发出 HTTP 请求,并将响应与 HTTP 请求的结果一起发回,

我使用 request-promise链接是这里的节点包,你可以看到下面的代码:

router.get("/url", function(req, res){
  let options = { url: "http//some-api-en-point", 
    method: "GET",
    resolveWithFullResponse: true
  };
  rp(options)
  .then(function(response) {
    if(response.statusCode == 200){
      res.send({"data":response.data})
    } else {
      res.status(404).json("data":"NOT FOUND");
    }
  })
  .catch(err => () => {
    res.send(err);
  })
});

来自http//some-api-en-point预期正文 (response.data) 是:

{ 
  "id": "3f3e2b23e96c5250441d4be2340010ed",
  "email": "let@example.com",
  "status": "1"
}

我使用 Mocha、Chai 和 Sinon 来运行单元测试,您可以在下面看到上述功能的单元测试用例:

describe('TEST: /URL', () => {
  it('it should return Status 200', (done) => { 
    chai.request(app)
      .get('/url')
      .end((err, res) => {
        sinon.stub(rp, 'Request').resolves({statusCode:200}); 
        expect(res).to.have.status(200);
        done();
      });
  });
});

当我运行npm test这个集成测试总是失败,需要弄清楚如何正确地存根。

这是集成测试:

server.ts

import express from 'express';
import { Router } from 'express';
import rp from 'request-promise';

const app = express();
const router = Router();

router.get('/url', function(req, res) {
  let options = { url: 'http//some-api-en-point', method: 'GET', resolveWithFullResponse: true };
  rp(options)
    .then(function(response) {
      if (response.statusCode == 200) {
        res.send({ data: response.data });
      } else {
        res.status(404).json({ data: 'NOT FOUND' });
      }
    })
    .catch(err => {
      res.send(err);
    });
});

app.use(router);

export { app };

server.spec.ts

import chai, { expect } from 'chai';
import chaiHttp from 'chai-http';
import sinon from 'sinon';
import proxyquire from 'proxyquire';
chai.use(chaiHttp);

const mData = {
  id: '3f3e2b23e96c5250441d4be2340010ed',
  email: 'let@example.com',
  status: '1'
};

describe('Test: /URL', () => {
  it('should return Status 200', done => {
    const mResponse = { statusCode: 200, data: mData };
    const mRp = sinon.stub().resolves(mResponse);
    const { app } = proxyquire('./server', {
      'request-promise': mRp
    });

    chai
      .request(app)
      .get('/url')
      .end((err, res) => {
        expect(err).to.be.null;
        expect(res).to.have.status(200);
        expect(mRp.calledWith({ url: 'http//some-api-en-point', method: 'GET', resolveWithFullResponse: true }));
        done();
      });
  });

  it('should return status 404', done => {
    const mResponse = { statusCode: 500, data: mData };
    const mRp = sinon.stub().resolves(mResponse);
    const { app } = proxyquire('./server', {
      'request-promise': mRp
    });

    chai
      .request(app)
      .get('/url')
      .end((err, res) => {
        expect(err).to.be.null;
        expect(res).to.have.status(404);
        expect(res.body).to.deep.equal({ data: 'NOT FOUND' });
        expect(mRp.calledWith({ url: 'http//some-api-en-point', method: 'GET', resolveWithFullResponse: true }));
        done();
      });
  });

  it('should send error', done => {
    const mError = 'network error';
    const mRp = sinon.stub().rejects(mError);
    const { app } = proxyquire('./server', {
      'request-promise': mRp
    });

    chai
      .request(app)
      .get('/url')
      .end((err, res) => {
        expect(err).to.be.null;
        expect(res.body).to.deep.equal({ name: 'network error' });
        expect(res).to.have.status(200);
        expect(mRp.calledWith({ url: 'http//some-api-en-point', method: 'GET', resolveWithFullResponse: true }));
        done();
      });
  });
});

100% 覆盖率的单元测试结果:

  Test: /URL
    ✓ should return Status 200 (1558ms)
    ✓ should return status 404 (116ms)
    ✓ should send error (90ms)


  3 passing (2s)

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

源代码: https : //github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57176000

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM