问题描述
我一直在成功使用 Knex 连接到后端数据库.但是我希望能够对我的代码进行单元测试.有没有办法模拟数据库连接?
I've been using Knex successfully to connect to a backend database. But I want to be able to unit test my code. Is there a way to mock the database connection?
我尝试使用 proxyquire ,但似乎无法正常工作.
I've tried using proxyquire but I can't seem to get it to work.
问题似乎与Knex的初始化方式有关.
The problem seems to be with the way Knex is initialized.
var knex = require('knex')({
client: 'mysql',
connection: {}
});
我设置了在我的单元测试中要模拟的knex.
I setup knex to be mocked in my unit test.
myService = proxyquire('../app/myService', {
'knex': knexProxy
});
我的服务包括knex.
My service includes knex.
var knex = require('knex').knex,
当我的服务运行查询时,它将失败.
When my service runs a query, it fails.
var sql = knex("table_name");
sql.insert(rowToInsert, "auto_increment_id");
sql.then(function (insertId) {
resolve();
}, function (err) {
reject(err);
});
由于某种原因,我似乎无法在尝试连接之前捕获该请求.
For some reason I just can't seem to capture the request before it attempts the connection.
我也尝试创建自定义Knex客户端,但这没有用还是.
I've also, tried to create a custom Knex Client, but that hasn't worked yet either.
推荐答案
使用笑话:
在您的应用程序根目录中创建文件/__mocks__/knex.js
:
Create the file /__mocks__/knex.js
in your app root:
module.exports = () => ({
select: jest.fn().mockReturnThis(),
from: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
first: jest.fn().mockReturnThis(),
then: jest.fn(function (done) {
done(null)
})
})
将所需的返回值传递给done
Pass the desired return value to done
这篇关于在针对Knex进行单元测试时,如何模拟假数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!