gpt4 book ai didi

node.js - 如何使用 Jest 来模拟 Knex

转载 作者:行者123 更新时间:2023-12-05 01:06:35 27 4
gpt4 key购买 nike

我正在尝试使用 jest 来模拟 knex 以进行以下实现

 const knex = Knex({ client: "mysql"})

const query = knex("table_name")
.where({
title: "xxx-yyy",
lang: "eng"
})
.select()
.orderBy('date', 'desc')
.toSQL()
.toNative()

下面我试过了,但是没用,出现错误“TypeError: knex is not a function”

jest.mock("knex", () => {
return () => {
return {
knex: () => {
where: () => {
select: () => {
orderBy: () => {
toSQL: () => {
toNative: jest.fn()
}
}
}
}
}
}
}
})

非常感谢您对此的任何帮助。

最佳答案

jest.mock() 将使用自动模拟版本模拟模块,factoryoptions 是可选的。

您可以使用 mockFn.mockReturnThis()模拟方法链接调用。

另外,如果你在模块范围内初始化Knex,你需要在设置mock之后require模块。

例如

index.js:

import Knex from 'knex';

const knex = Knex({ client: 'mysql' });

export function main() {
const query = knex('table_name')
.where({
title: 'xxx-yyy',
lang: 'eng',
})
.select()
.orderBy('date', 'desc')
.toSQL()
.toNative();
}

index.test.js:

import Knex from 'knex';

jest.mock('knex');

describe('68717941', () => {
test('should pass', () => {
const querybuilder = {
where: jest.fn().mockReturnThis(),
select: jest.fn().mockReturnThis(),
orderBy: jest.fn().mockReturnThis(),
toSQL: jest.fn().mockReturnThis(),
toNative: jest.fn(),
};
const mKnex = jest.fn().mockReturnValue(querybuilder);
Knex.mockReturnValue(mKnex);
const { main } = require('./');
main();
expect(Knex).toBeCalledWith({ client: 'mysql' });
expect(mKnex).toBeCalledWith('table_name');
expect(querybuilder.where).toBeCalledWith({ title: 'xxx-yyy', lang: 'eng' });
expect(querybuilder.select).toBeCalledTimes(1);
expect(querybuilder.orderBy).toBeCalledWith('date', 'desc');
expect(querybuilder.toSQL).toBeCalledTimes(1);
expect(querybuilder.toNative).toBeCalledTimes(1);
});
});

测试结果:

 PASS  examples/68717941/index.test.js (8.844 s)
68717941
✓ should pass (7464 ms)

----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.439 s

关于node.js - 如何使用 Jest 来模拟 Knex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68717941/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com