【问题标题】:Stub mongoDB with hapijs使用 hapijs 存根 mongoDB
【发布时间】:2017-10-14 08:42:20
【问题描述】:

我试图弄清楚如何在hapi js 中存根mongoDB 以允许测试,但我不知道该怎么做。我试过检查Sinonjs,但我不知道如何在这种特殊情况下应用它。 以下是部分代码:

// index.js
'use strict';

const Hapi = require('hapi');
const MongoJS = require('mongojs');

const server = new Hapi.Server();

server.connection({ host: 'localhost', port: 11001 });

server.app.db = MongoJS('crunchbase', ['companies']);

server.register([
  {
    register: require('./lib/plugins')
  },
  {
    register: require('./lib/modules/companies'),
    options: {
      baseUrl: '/v1/companies'
    }
  }
], (err) => {

  if (err) {
    throw err;
  }

  server.start((err) => {

    if (err) {
      throw err;
    }
    server.log('info', `Server listening on ${server.info.uri}`);
  });
});

module.exports = server;

以下是路线:

// companies.js
'use strict';

const Boom = require('boom');
const Joi = require('joi');

const error = Joi.object().keys({
  statusCode: Joi.number(),
  error: Joi.string(),
  message: Joi.string()
});

const schema = Joi.object().keys({
  _id: Joi.object(),
  permalink: Joi.string(),
  name: Joi.string(),
  homepage_url: Joi.string(),
  category_list: Joi.string(),
  funding_total_usd: Joi.alternatives().try(Joi.number(), Joi.string()),
  status: Joi.string(),
  country_code: Joi.string().allow(''),
  state_code: Joi.alternatives().try(Joi.string(), Joi.number()).allow(''),
  region: Joi.string().allow(''),
  city: Joi.string().allow(''),
  funding_rounds: Joi.number(),
  founded_at: Joi.string().allow(''),
  first_funding_at: Joi.string(),
  last_funding_at: Joi.string()
});

exports.register = (server, options, next) => {

  const db = server.app.db;
  const { baseUrl } = options;

  server.route([
    {
      method: 'GET',
      path: baseUrl,
      config: {
        description: 'companies',
        notes: 'Get a list of companies from the database',
        tags: ['api'],
        validate: {
          query: {
            limit: Joi.number().min(1).max(20).default(5)
          }
        },
        response: {
          status: {
            200: Joi.array().items(schema),
            400: error,
            500: error
          }
        }
      },
      handler: (request, reply) => {

        db.companies.find().limit(request.query.limit, (err, docs) => {

          if (err) {
            return reply(Boom.wrap(err, 'Internal MongoDB error.'));
          }
          reply(docs);
        });
      }
    }
  ]);

  return next();
};

exports.register.attributes = {
  pkg: require('./package.json')
};

这是测试套件:

// companies.test.js
'use strict';

const Code = require('code');
const Lab = require('lab');

const lab = exports.lab = Lab.script();
const { describe, it } = lab;
const expect = Code.expect;

const Server = require('../../');

describe('Companies module test suite', () => {

  const baseUrl = '/v1/companies';

  it('should return array of 5 companies by default', (done) => {

    Server.inject({
      method: 'GET',
      url: baseUrl
    }, (response) => {

      expect(response.statusCode).to.equal(200);
      expect(response.result).to.be.an.array().and.have.length(5);
      done();
    });
  });

  it('should return array of 3 companies', (done) => {

    Server.inject({
      method: 'GET',
      url: baseUrl + '?limit=3'
    }, (response) => {

      expect(response.statusCode).to.equal(200);
      expect(response.result).to.be.an.array().and.have.length(3);
      done();
    });
  });

  it('should throw an error', (done) => {

    Server.inject({
      method: 'GET',
      url: baseUrl + '?limit=me'
    }, (response) => {

      expect(response.statusCode).to.equal(400);
      expect(response.result.error).to.equal('Bad Request');
      done();
    });
  });
});

它有效,但前提是存在与我想要解耦的数据库的连接。任何帮助将不胜感激。

【问题讨论】:

    标签: mongodb testing sinon hapijs


    【解决方案1】:

    这是devinivy提供的解决方案

    我采用的一种方法是将查询放在服务器方法中,然后 在我的测试中存根服务器方法(server.methods.x = stubX)

    您也可以按照timcosta 的建议查看proxyquire

    这是简短的github discussion

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-05
      • 2014-04-20
      相关资源
      最近更新 更多