REST API 在 nodejs 中使用 promise return 进行单元测试

REST API unit test with promise return in nodejs

我在 class 中有一个调用 REST api 和 returns Promise 的函数 object.I 我能够测试 Promise 对象,但我不确定我们如何才能存根或模拟休息 api 调用和测试。

Token.js

class Token {

  getToken(payload) {
    let outahToken = new Promise(function (resolve, reject) {
      request('hhtps://xyz.com', function (err, res, body) {
        if (err) {
          reject(err);
        } else {
          console.log(res);
          resolve(body);
        }
      })
    });

    return outahToken;
  }
}
module.exports = Token;

Token.test.js

'use strict'

const chai = require("chai");
const expect = chai.expect;
const nock = require('nock');
const sinon = require("sinon");
const Token = require('Token');
describe('Get User tests', () => {
  let Token;
  beforeEach(() => {
    outhController = new Token();
    sinon.stub(Token, 'getToken').returns(Promise.resolve({
      name: "All"
    }));

  });

  it('Outh test', (done) => {
    Token.getToken(payload)
      .then(response => {
        expect(typeof response).to.equal('object');
        done();
      });
  });
});        

我们可以使用 proxyquire 模拟请求模块并检查它是否使用正确的参数调用。我们需要 proxyquire,因为请求模块导出一个函数 request(),仅用 Sinon 更难模拟。

并且因为请求方法是一个回调函数,我们可以使用 Sinon yields 来模拟它。

const chai = require('chai');
const sinon = require('sinon');
const proxyquire = require('proxyquire');

const expect = chai.expect;

describe('Token test', function() {
  let outhController;
  let Token;
  let requestStub;

  beforeEach(() => {
    const err = null;
    const res = null;
    const body = { name: 'All' };

    requestStub = sinon.stub().yields(err, res, body); // create sinon for request function and return response body that we want
    Token = proxyquire('Token', { request: requestStub }) // replace original request module with our sinon stub

    outhController = new Token();
  });

  it('Outh test', (done) => {
    const payload = {};
    outhController.getToken(payload)
      .then(response => {
        sinon.assert.calledWith(requestStub, 'hhtps://xyz.com');

        expect(typeof response).to.equal('object');
        expect(response.name).to.equal('All');

        done();
      });
  });
});

希望对您有所帮助