- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试测试一个使用 knex
的 node.js
函数。
不只是模拟 knex
,我认为在内存数据库上实际运行测试很有趣,这使得这个测试不是严格单一的,但对我来说,这是唯一有用的方法测试一个 repository
类。
这也是这里投票最多的答案:https://stackoverflow.com/a/32749601/1187067
knex
bookRepo.js
bookRepo.test.js
注入(inject)一个基于 SQLite3
的 knex
连接。数据库初始化良好,测试成功,afterEach()
函数调用正常,但过程永不结束,这对管道来说尤其成问题。
我发现停止进程的唯一方法是在 bookRepo.js 和 bookRepo.test.js 中调用 knex.destroy()
,但不可能销毁 knex,因为它赢了可以多次使用它。
感谢您的帮助!
bookRepo.js
const knex = require('connection'); // dependency not injected in constructor
const TABLE = 'books';
class BookRepo {
constructor() {
this.knex = knex;
}
static getTable() {
return TABLE;
}
async getTitleById(id) {
const book = await this.knex(TABLE)
.select('title')
.where('id', id)
.first();
return book.title;
}
}
module.exports = BookRepo;
bookRepo.test.js
const { assert } = require('chai');
const mock = require('mock-require');
const {
describe,
it,
before,
after,
beforeEach,
afterEach,
} = require('mocha');
const sqliteConf = {
client: 'sqlite3',
connection: {
filename: ':memory:',
},
useNullAsDefault: true,
};
const knex = require('knex')(sqliteConf);
const booksTable = BookRepo.getTable();
const BOOK_1 = {
id: 1,
title: 'Batman',
};
let bookRepo;
describe('getTitleById', () => {
before(() => {
// To use sqlite3 in the tested module, replace knexfile (required by connections)
mock('../knexfile', {
development: sqliteConf,
});
// as knex is not injected in constructor, we need to require BookRepo after having mocked knexfile.
const BookRepo = require('../bookRepo');
bookRepo = new BookRepo();
});
after(() => {
mock.stopAll();
knex.destroy(); // destroys only the connection of the test, not in bookRepo
});
/**
* We initialize the SQLite database before each test (create table and insert)
*/
beforeEach(async () => {
// drop table
await knex.schema.dropTableIfExists(booksTable);
// create table
await knex.schema.createTable(booksTable, (table) => {
table.integer('id');
table.string('title');
});
// Insertion
await knex.transaction((t) => knex(booksTable)
.transacting(t)
.insert(BOOK_1)
.then(t.commit)
.catch(t.rollback))
.catch((e) => {
console.error(e);
throw new Error('failed to insert test data');
});
});
/**
* We drop the SQLite table after each test
*/
afterEach(async () => {
await knex.schema.dropTableIfExists(booksTable); // table well dropped
});
it('returns the title of the given book', async () => {
const bookRepo = new BookRepo();
const expectedTitle = BOOK_1.title;
const retrievedTitle = await bookRepo.getTitleById(BOOK_1.id);
assert.equal(retrievedTitle, expectedTitle); // OK
});
});
package.json
…
dependencies": {
"knex": "^0.20.1",
},
"devDependencies": {
"chai": "latest",
"mocha": "^6.2.2",
"sqlite3": "latest",
}
}
最佳答案
由于您使用的是 mocha,因此最好使用 Mocha 的 after
hook并从那里调用 destroy
。同样,您可以在 before
中实例化 Knex。我想不出您需要在非测试代码中调用 destroy
的原因。
关于node.js - 使用 knex 和 sqlite3 的 node.js 方法测试永远不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58651587/
knex.raw(sql, bindings)和 knex.schema.raw(statement) . 似乎这两个函数具有不同的签名。 如果它们相等,我该如何使用 knex.schema.raw(
我有一些 Knex 迁移脚本,如下所示: 'use strict'; exports.up = function (knex) { return knex.schema .ha
我希望基本上在 Knex 中进行此类查询,但我无法使其正常工作: select distinct * from ( select *, 1 as rank from table1 where Wo
我想为 Knex 迁移中的主键设置默认值,但我遇到了问题。这是我最初的迁移: exports.up = (knex, Promise) => { return knex.schema.create
我发现有两种方法可以在迁移文件中编写 knex 迁移。 exports.up = function (knex) { return knex.schema .createTable
我正在使用 MSSQL,我有一个存储过程返回多个结果集(1 个用于数据,1 个用于记录计数)当我使用 knex.raw 调用此存储过程时,Knex 仅返回第一个结果集。如何使用 Knex + Node
我有一个表,当向其中添加新行时,所有现有行都需要更新。本质上,在一个“插入”完成之前,我不想让另一个“插入”发生。 所以我猜普通的行级锁或读锁是不够的,想在事务期间直接锁表。 有没有办法在 Knex
我正在尝试使用以下代码在迁移脚本中将列数据类型从日期修改为时间戳 knex.schema.alterTable('user', function(t) { t.timestamp('bifthda
我的 Knex 驱动程序出现间歇性错误: TimeoutError: Knex: 获取连接超时。游泳池可能已经满了。你错过了一个 .transacting(trx) 调用吗? 我猜,要么是我的 RDS
我有以下路线,我想获取与从第一个查询获得的 id 关联的总和 app.post('/VerEmpresas', function (req, res) { var r, dot, ide; k
在How to return a plain value from a Knex / Postgresql query? ,我询问了如何从 Knex 查询中获取列值,而没有包含列名的 JSON 对象。
我对 knex(和 node js)很陌生。如果存在,我需要编写插入,但我无法执行此操作。 下面不起作用,但有没有办法做到这一点? var val = "water"; knex('ingredien
有没有办法使用 Kenx 将 IF 语句添加到 SELECT 查询?假设我要执行以下查询: SELECT id, name, IF(grade<60,'Fail','Pass') AS examRes
我有一个关于 SQL 连接池的问题。我的团队正在我们的 Node 应用程序之一中使用 knex.js 库来进行数据库查询。应用程序不时需要切换数据库。因此,我的团队创建了一个初始化函数,该函数返回配置
我刚刚接触 knex,遇到了事务。我认为它很有用,因为它具有回滚功能。尝试使用它(参见下面的代码) await knex.transaction(trx => { knex.raw(delete fr
我正在为 Mysql 使用 Knex.js。我运行迁移并成功创建表。之后,当我通过此命令命令 knex seed:run 运行种子时,出现以下错误: Knex:warning - calling kn
我通过以下方式将 order by 绑定(bind)添加到 knex 原始查询。 -- Here userIds = [1,2,3] and dataOrder='DESC' knex.raw.que
尝试针对我的远程 postgres 数据库(不是本地主机)运行 knex seed:run 时出现以下错误:Knex:Error Pool2 - Error: connect ECONNREFUSED
我要在一个函数中对数据库执行五 (5) 项操作。我想将它们放入事务中,但我发现将每个都放入前一个操作的回调中有点奇怪。我怎样才能以优雅和可读的方式做到这一点? 最佳答案 Knex 具有内置的事务支持,
我正在尝试使用 Knex.js 查询生成器构建数据库迁移,但是我收到以下与外键关系相关的错误: Knex:warning - migrations failed with error: alter t
我是一名优秀的程序员,十分优秀!