我正在尝试在 React 应用程序中为 Postgres 编写一些基本测试装置。
我有一些设置和拆卸 SQL 文件:
-- ### Setup File ###
DROP TABLE IF EXISTS "requests";
-- This script only contains the table creation statements and does not fully represent the table in the database. It's still missing: indices, triggers. Do not use it as a backup.
-- Sequence and defined type
CREATE SEQUENCE IF NOT EXISTS requests_id_seq;
-- Table Definition
CREATE TABLE "requests" (
"id" int4 NOT NULL DEFAULT nextval('requests_id_seq'::regclass),
"status" varchar(10),
"requestor" varchar(255),
"template_id" varchar(255),
"version" varchar(10),
"detail" text,
PRIMARY KEY ("id")
);
-- ### Teardown File ###
DROP TABLE IF EXISTS "requests" CASCADE;
DROP SEQUENCE IF EXISTS "requests_id_seq" CASCADE;
在测试中使用 dbtools.js
调用它们辅助文件:
/*eslint no-console: ["error", { allow: ["warn", "error"] }]*/
const Pool = require('../../db');
require('dotenv').config(); // Load .env file
//eslint-disable-next-line no-undef
const {PGUSER, PGPASSWORD, PGDATABASE, PGHOST, PGPORT} = process.env;
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const create_sql = 'bin/sql/tables_setup.sql';
const droptables_sql = 'bin/sql/tables_down.sql';
function execute_sql_file(fileName){ //eslint-disable-line no-unused-vars
exec(
`PGPASSWORD="${PGPASSWORD}" psql -U ${PGUSER} -h ${PGHOST} -p ${PGPORT} -d ${PGDATABASE} -f ${fileName}; exit 0`,
function(err){
if (err !== null) {
console.error('Error populating db: ' + err);
}
}
);
}
function prepare_db(){
execute_sql_file(create_sql);
}
function clean_db(){
execute_sql_file(droptables_sql);
}
module.exports = { prepare_db, clean_db };
用于 app.test.js
文件:
...
beforeEach(async () => {
await prepare_db();
});
afterEach(async () => {
await clean_db();
});
...
当执行时,路由从 Postman 命中,第一次一切正常,第二次失败。
好像是dropping table,没问题,但是re-setting不行。当我手动运行安装文件 ( psql webui -U postgres < /Users/dd/webui/backend/bin/sql/tables_setup.sql
) 时,它工作正常。有什么明显的地方我做错了吗?
(此外 - 这次请不要双关语,我不想使用 Mocks)
最佳答案
编辑
在重新阅读您的问题后,我意识到我的以下观察结果可能实际上不是您所追求的,因为您可能想在实际 beforeEach()
中运行数据库的设置/拆卸。/afterEach()
.
我注意到你的 exec()
函数启动了一个 promise ,但实际上并没有await
为此,请尝试:
async function execute_sql_file(fileName){ //eslint-disable-line no-unused-vars
await exec(
`PGPASSWORD="${PGPASSWORD}" psql -U ${PGUSER} -h ${PGHOST} -p ${PGPORT} -d ${PGDATABASE} -f ${fileName}; exit 0`,
function(err){
if (err !== null) {
console.error('Error populating db: ' + err);
}
}
);
}
忽略下面的观察结果。
尝试设置/拆除 before()
中的数据库/after()
方法,不在 beforeEach()
中/afterEach()
:
...
before(async () => {
await prepare_db();
});
after(async () => {
await clean_db();
});
...
关于node.js - Postgres 和 NodeJS 的测试装置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58074418/