如何使用module.exports在函数内部模拟pg.pool

时间:2020-11-02 15:18:19

标签: javascript jestjs

我的考试有问题。

我在这里有这些功能:

// utils.js

const pg = require('pg')

const defaultHandle = {
    success: (res, result) => res.status(200).send((result || []).rows),
    error: (res, err) => res.status(400).send(err)
}


const makePool = async (res, query, queryHandle = {}, values) => {
    const handleFunctions = {...defaultHandle, ...queryHandle}
    return await pool
        .query(query, values)
        .then(result => {
            if (result) {
                return handleFunctions.success(res, result)
            }
            if (!result) {
                console.log(query)
                return query
            }
        })
        .catch(err => {
            console.log(err, query)
            return handleFunctions.error(res, err)
        })
}

module.exports = {
    makePool: makePool,
}

// currentPeople.js

const handleParams = require('../utils').handleParams
const makePool = require('../utils').makePool

const getPeople = (req, res, anotherFunction) => {
    makePool(
        res,
        `
        SELECT
        age
        FROM table_1
  `
    )
}
const currentPeople = async (req, res, anotherFunction) => {
    return getPeople(req, res, anotherFunction)
}

我想模拟getPeople中的值,我已经做了这样的事情:

import * as allFunction from '../currentPeople';
import pg from 'pg'

jest.mock('pg')

jest.spyOn(allFunction, 'getPeople').mockResolvedValue({rows: [{name: 'aaaaa'}]})

但是它不起作用,我继续收到age作为值...

有人可以帮我吗?

编辑1: 我试过了,但是也没用。

function mockFunctions() {
    const original = jest.requireActual('../getPeople')
    return {
        ...original,
        makePool: () => Promise.resolve([{domain_name: '1234'}])
    }
}
jest.mock('../getPeople', () => mockFunctions())

我收到:

    : Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:

0 个答案:

没有答案