首页 > 解决方案 > Nock 无法使用 chai-http 和 mocha 捕获 post 请求

问题描述

我正在创建一个与 API 连接的 Web 应用程序,以便进行登录和一些操作,目前我正在尝试使用,和./authenticate在我的应用程序上测试路由。chaichai-httpnock

var chai = require('chai');        
var expect = chai.expect;
var chaiHttp = require('chai-http');
var nock = require('nock');

chai.use(chaiHttp);

describe('/authenticate', function() {
var agent = chai.request.agent('http://localhost:3000');

  afterEach(function() {
    agent.close();         
    nock.cleanAll();       
  });

  describe('User authorized', function() {
    it('redirects to /dashboard', function() {
      // I'm trying to mock the response here but is not working.
      nock('http://the.api.com:8080')
      .post('/v1/authenticate')
      .reply(201, {
        'authorized': true,
        'jwt': 'thejwtasdf'
      });
      agent
      .post('/authenticate')
      .send({ email: 'test@gmail.com', password: 'TheAmazingPass' })
      .then(function(res) {
        expect(res).to.redirectTo('http://localhost:3000/dashboard');
        expect(res.text).to.match(/Dashboard/);
      })
      .catch(function(e) { console.log(e);  });
    });
  });
});

测试通过但我得到了这个捕获的错误,根据这个,页面没有被重定向,因为调用没有被nock捕获,它被直接发送到API:

{ AssertionError: expected redirect with 30X status code but got 200
  at Proxy.<anonymous>
  ... rest of the error omitted.

但是当我使用真实有效的电子邮件和密码时,此测试通过,没有发现错误:

var chai = require('chai');
var expect = chai.expect;
var chaiHttp = require('chai-http');
var nock = require('nock');

chai.use(chaiHttp);

describe('/authenticate', function() {
  var agent = chai.request.agent('http://localhost:3000')

  afterEach(function() {
    agent.close();
    nock.cleanAll();
  });

  describe('User authorized', function() {
    it('redirects to /dashboard', function() {
      agent
      .post('/authenticate')
      .send({ email: 'realemail@gmail.com', password: 'RealPass'  })
      .then(function(res) {
        expect(res).to.redirectTo('http://localhost:3000/dashboard');
        expect(res.text).to.match(/Dashboard/);
      })
      .catch(function(e) { console.log(e);  });
    });
  });
});

有了这段代码,测试就通过了,我是否错过了诺克的东西?

=== 编辑 ===

这是我要测试的代码:

这是我的登录路由器(flashMessages 是一个自定义中间件,有助于处理 flash 消息)。

var loginService = require('../services/login');
var flashMessages = require('../utils/flash_messages').flashMessages;
var router = require('express').Router();

// check if user is logged in
var sessionChecker = function(req, res, next) {
  if (req.session.auth && req.cookies.user_sid) {
    res.redirect('/dashboard');
  } else {
    next();
  }
};

router.get('/', sessionChecker, flashMessages, function(req, res, next){
  res.render('login', {
    title: 'Welcome',
    errors: res.locals.flash.errors,
    typeError: res.locals.flash.errorType,
  });
});

router.post('/authenticate', function(req, res, next){
  req.checkBody('email', 'Email is required').notEmpty();
  req.checkBody('email', 'Invalid email format').isEmail();
  req.checkBody('password', 'Password is required').notEmpty();
  req.getValidationResult().then(function(result){
    if (result.isEmpty()) {
      loginService.authenticate(req.body).then(function(result){
        if (result.authorized){
          // success
          req.session.auth = result;
          req.session.auth.user = loginService.currentUser(result.jwt)
          res.redirect('/dashboard');
        } else {
          // user not found error
          req.session.flash = {
            errors: [{msg: result.msg}],
            errorType: 'anotherError'
          };
          res.redirect('/');
        }
      }).catch(function(e){
        // server errors
        req.session.flash = {
          errors: [e],
          errorType: 'anotherError'
        };
        res.redirect('/');
      });
    } else {
      //validation errors
      req.session.flash = {
        errors: result.array(),
        errorType: 'validationError'
      };
      res.redirect('/');
    }
  });
});

module.exports = router;

登录路由器使用 loginService,这是与登录一起使用的部分:

var httpReq = require('../utils/http_requests');

module.exports.authenticate = function(params){
  return new Promise(function(resolve, reject) {
    httpReq.callToAPI(params, {
      path: '/v1/authenticate',
      method: 'POST'
    })
    .then(function(authorization) {
      resolve(JSON.parse(authorization));
    })
    .catch(function(err) {
      reject(err);
    });
  });
};

module.exports.currentUser = function(shaCode){
  return JSON.parse(Buffer.from(shaCode.split('.')[1], 'base64').toString());
};

最后我有一个用于 http 请求的工具:

var http = require('http');

function createOptions(options) {
  headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Connection': 'close'
  };
  if (options.jwt) { headers['Authorization'] = 'Bearer ' + options.jwt; }
  return {
    hostname: 'the.api.com',
    port: 8080,
    path: options.path,
    method: options.method,
    headers: headers
  };
};

module.exports.callToAPI = function(params, options) {
  reqObj = createOptions(options);
  return new Promise(function(resolve, reject) {
    body = [];
    req = http.request(reqObj, function(res) {
      res.on('data', function(chunk) {
        body.push(chunk);
      });
      res.on('end', function() {
        console.log(body.join(''));
        resolve(body.join(''));
      });
    });
    req.on('error', function(err) {
      reject({ msg: "We're sorry, but something went wrong" });
    });
    if (params) { req.write(JSON.stringify(params)); }
    req.end();
  });
};

任何帮助将不胜感激。

问候。

标签: node.jsexpressmocha.jsnockchai-http

解决方案


推荐阅读