gpt4 book ai didi

unit-testing - 如何用玩笑模拟 pg-promise 库

转载 作者:行者123 更新时间:2023-12-01 04:44:52 25 4
gpt4 key购买 nike

我正在尝试模拟 pg promise 库。无论 promise 是拒绝还是解决,我都希望能够模拟返回。这是一个示例函数和测试:

const pgp = require('pg-promise')({});

const someFunc = callback => {
const db = pgp('connectionString');
db
.none('create database test;')
.then(() => {
callback(null, 'success');
})
.catch(err => {
callback(err);
});
};

module.exports = {
someFunc
};

我想像这样测试它:
const { someFunc } = require('./temp');
let pgp = require('pg-promise')({
noLocking: true
});
// HOW TO MOCK?

describe('test', () => {
beforeEach(() => {
jest.resetModules();
jest.resetAllMocks();
});
it('should test', () => {
let db = pgp('connectionString');
// how to mock this?

db.none = jest.fn();
db.none.mockReturnValue(Promise.reject('mock'));
const callback = jest.fn();
someFunc(callback);
return new Promise(resolve => setImmediate(resolve)).then(() => {
expect(callback.mock.calls.length).toEqual(1);
});
});
});

最佳答案

您可以模拟 pgp像这样一个愚蠢的模拟对象:

const { someFunc } = require('./temp');
let pgp = jest.fn(() => ({
none: jest.fn(),
})

jest.mock('pg-promise') // Jest will hoist this line to the top of the file
// and prevent you from accidentially calling the
// real package.

describe('test', () => {
beforeEach(() => {
jest.resetModules();
jest.resetAllMocks();
});

it('should test', () => {
let db = pgp('connectionString');
db.none.mockRejectedValue('mock'); // This is the mock
const callback = jest.fn();
someFunc(callback);
return new Promise(resolve => setImmediate(resolve)).then(() => {
expect(callback.mock.calls.length).toEqual(1);
});
});
});

关于unit-testing - 如何用玩笑模拟 pg-promise 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47456900/

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