[英]Postgres/Knex “insert or update on table ”locations“ violates foreign key constraint”
[英]How to handle foreign key constraint with Jest/Supertest/Knex/Postgres
我正在尝试开始为我的应用程序编写测试。 我正在使用 Jest & Supertest 来运行我所有的测试。 当我尝试运行我的测试套件时,我收到有关外键约束的错误。
错误:
error: truncate "users" restart identity - cannot truncate a table referenced in a foreign key constrainterror: cannot truncate a table referenced in a foreign key constraint
这是我的 server.spec.js 文件:
const request = require('supertest');
const server = require('./server.js');
const db = require('../data/db-config.js');
describe('server.js', () => {
describe('POST /register', () => {
it('should return 201 created', async () => {
const user =
{
name: "test",
username: "test",
email: "test77@test.com",
password: "password"
}
const res = await request(server).post('/api/auth/register').send(user);
expect(res.status).toBe(201);
})
beforeEach(async () => {
await db("graphs").truncate();
await db("users").truncate();
});
})
})
这是我的 knex 迁移文件:
exports.up = function(knex) {
return (
knex.schema
.createTable('users', tbl => {
tbl.increments();
tbl.string('username', 255).notNullable();
tbl.string('password', 255).notNullable();
tbl.string('name', 255).notNullable();
tbl.string('email', 255).unique().notNullable();
})
.createTable('graphs', tbl => {
tbl.increments();
tbl.string('graph_name', 255).notNullable();
tbl.specificType('dataset', 'integer[]').notNullable();
tbl
.integer('user_id')
.unsigned()
.notNullable()
.references('id')
.inTable('users')
.onDelete('CASCADE')
.onUpdate('CASCADE');
})
)
};
exports.down = function(knex) {
return (
knex.schema
.dropTableIfExists('graphs')
.dropTableIfExists('users')
)
};
我在研究中遇到了这个答案: 如何测试与外键链接的表?
我是 Postgres 和测试的新手。 我需要像在迁移中那样以相反的顺序删除表是有道理的。 但是,当我尝试在测试的beforeEach
部分中截断它们时,表的列出顺序似乎无关紧要。
我不确定从这里到底该去哪里。 任何帮助将不胜感激。
我认为这里的诀窍是使用一些knex.raw
:
await db.raw('TRUNCATE graphs, users RESTART IDENTITY CASCADE');
CASCADE
因为您不希望外键约束妨碍您,而RESTART IDENTITY
因为默认 Postgres 行为不是重置序列。 请参阅截断。
当我们讨论一个相关主题时,请允许我介绍一些可能会让您的生活更轻松的东西:模板数据库! 模板是 Postgres 可以用来从已知状态(通过复制)非常快速地重新创建数据库的数据库。 这甚至可以比截断表更快,并且它允许我们在测试时跳过所有烦人的外键内容。
例如,您可以使用raw
执行以下操作:
DROP DATABASE testdb;
CREATE DATABASE testdb TEMPLATE testdb_template;
这是一种非常便宜的操作,非常适合测试,因为每次进行测试运行时,您都可以从一个已知状态(不一定是空状态)开始。 我想需要注意的是,您的knexfile.js
将需要指定与用户的连接,该连接具有足够的凭据以创建和删除数据库(因此可能是仅知道localhost
的“管理员”连接),并且必须创建和维护模板。 有关更多信息,请参阅 模板数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.