【问题标题】:Mocha tests can't connect to postgres database, using knex摩卡测试无法连接到 postgres 数据库,使用 knex
【发布时间】:2019-07-06 13:18:43
【问题描述】:

我正在尝试在 nodejs express 应用程序中使用 mocha 为通过 knex 与 postgres 数据库交互的函数实现一些集成测试。 这些功能在 mocha 之外工作 - 我可以在 node 或 nodemon 中启动应用程序,通过 Postman 提交请求,从数据库中检索记录,添加新记录等。但是当我尝试通过 mocha 测试代码时,我得到了类似的错误以下是尝试访问数据库的任何函数:

 select * from "item" where "user_id" = $1 - relation "item" does not exist

数据库连接的环境变量设置为连接正确的数据库;当我手动端到端测试应用程序时,一切正常;我从数据库中取回数据。

我在下面包含了我认为相关的代码 sn-ps:其中一个无法运行的测试的测试脚本、我正在尝试测试的函数以及该函数所依赖的模块.

测试脚本

const Item = require('../db/item');
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');

// set up the middleware
chai.use(chaiAsPromised);
var should = require('chai').should() 

describe('Item.getByUser', function() {
  contex`enter code here`t('With valid id', function() {
    const item_id = 1;
    const expectedResult = "Canoe";
    it('should return items', function() {
      return Item
      .getByUser(item_id)
      .then(items => {
        items[0].name.should.equal(expectedResult);
        });    
      });  
    });

ITEM.GETBYUSER 函数的片段:

const knex = require('./connection');

module.exports = {

  getByUser: function(id) {
    return knex('item').where('user_id', id);
  },

来自连接模块的片段:

require('dotenv-safe').config();
const environment = process.env.NODE_ENV || 'development';
const config = require('../knexfile')[environment];
module.exports = require('knex')(config);

来自 KNEXFILE 模块的片段:

module.exports = {

  development: {
    client: 'pg',
    connection: process.env.DATABASE_URL
  },
  production: {
    client: 'pg',
    connection: process.env.DATABASE_URL 
  }

};

我得到的上述测试的错误信息是:

1) Item.getByUser
       With valid id
         should return items:
     select * from "item" where "user_id" = $1 - relation "item" does not exist
  error: relation "item" does not exist
      at Connection.parseE (node_modules\pg\lib\connection.js:567:11)
      at Connection.parseMessage (node_modules\pg\lib\connection.js:391:17)
      at Socket.<anonymous> (node_modules\pg\lib\connection.js:129:22)
      at addChunk (_stream_readable.js:284:12)
      at readableAddChunk (_stream_readable.js:265:11)
      at Socket.Readable.push (_stream_readable.js:220:10)
      at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)

【问题讨论】:

    标签: postgresql mocha.js knex.js


    【解决方案1】:

    好的,看起来这实际上与数据库的环境变量有关,我不太明白。尽管我将数据库连接设置为“postgres://localhost/mydatabase”,但当我实时测试 db(包括通过 knex 命令迁移和播种数据库)时实际使用的数据库是“postgres://localhost/username” -与“mydatabase”的所有者同名的数据库。但我认为 mocha 测试试图连接到 mydatabase,此时它仍然是空的,因为 migrate 和 seed 影响了数据库的“用户名”。

    所以,我认为这可以关闭。我将尝试复制连接到错误数据库的问题;不确定这是怎么发生的,因为我从来没有故意将连接或任何环境变量设置为“postgres://localhost/username”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-14
      • 1970-01-01
      • 2017-11-12
      • 2016-02-26
      • 2013-04-21
      • 2021-07-10
      • 1970-01-01
      • 2016-08-25
      相关资源
      最近更新 更多