![](/img/trans.png)
[英]Passing arguments to a function which is created using the new function keyword in javascript
[英]Jest - trying to mock db connection that is created in a function using new keyword
我有以下从 mssql 中获取数据的代码。 有什么办法可以模拟连接池吗? 我想让 pool.request().execute() 调用返回一些模拟数据。 我不认为这是可能的,我目前正在努力思考如何测试这个 function。
我能想到的唯一解决方案是将 ioc 用于连接池。 但在我提前 go 之前,我只想确保不可能模拟连接池。
谢谢
const fetchData ({args}) => {
const pool = await new ConnectionPool(conn.getConfig()).connect();
const result = await pool.request().input(...args).execute('Get_Some_Data');
pool.close();
// business logic below I want to test
...
...
}
我一直在谷歌搜索并检查文档。 我不认为这是可能的,但我想确认一下。
您可以使用 `jest.fn().mockImplementation() 模拟构造函数。 在文档中阅读更多相关信息。
const mockPool = {
connect: () => mockPool,
request: () => mockPool,
input: () => mockPool,
execute: () => {
console.log("Called mock execute");
return [1, 2, 3];
},
close: () => console.log("Closed")
}
const ConnectionPool = jest.fn().mockImplementation(() => mockPool)
我假设您正在使用来自mssql
package 的ConnectionPool
。
const {ConnectionPool} = require("mssql");
const fetchData = async ({args}) => {
const pool = await new ConnectionPool(conn.getConfig()).connect();
const result = await pool.request().input(...args).execute('Get_Some_Data');
pool.close();
// business logic
return result;
}
const {fetchData} = require('./fetch-data');
jest.mock('mssql', ()=> {
const mockPool = {
connect: () => mockPool,
request: () => mockPool,
input: () => mockPool,
execute: () => {
console.log("Called mock execute");
return [1, 2, 3];
},
close: () => console.log("Closed")
}
return {
ConnectionPool: jest.fn().mockImplementation(() => mockPool)
}
});
it('Mock Connection Pool', async () => {
const data = await fetchData({args: []});
expect(data).toStrictEqual([1, 2, 3]);
});
谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.