首页 > 解决方案 > 摩卡测试无法连接到 postgres 数据库,使用 knex

问题描述

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

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

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

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

测试脚本

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)

标签: postgresqlmocha.jsknex.js

解决方案


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

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


推荐阅读