如何模拟带参数的模块

时间:2018-03-22 10:50:48

标签: node.js jestjs pg-promise

我正在尝试为使用pg-promise的代码编写单元测试,它看起来像这样:

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

const cn = {
  host: process.env.DB_HOST,
  port: 5432,
  database: process.env.DB_NAME,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD
};

function insertStuff(stuff) {
  let db = pgp(cn);
  return db.one('INSERT INTO test(stuff) VALUES ($1) RETURNING id, stuff', [stuff])
    .then(data => {
      return data
    })
 }
 module.exports.insertStuff = insertStuff

测试代码如下所示:

const mockFakeDb = {
  one: jest.fn()
}

jest.mock("pg-promise", () => {
  return mockFakeDb
})

 const insertStuff = require("../src/db-utils").insertStuff

 test("params for inserting stuff are correct", done => {
   mockFakeDb.one.mockImplementationOnce(() => {
    return Promise.resolve({id: 123456789, stuff: "stuff"})

   insertStuff("stuff").then((data) => {
   const insertCall = fakeDb.one.mock.calls[0]
   expect(insertCall).toHaveBeenCalledTimes(1)
   done()
 })
})

所以在试图模仿pg-promise时我得到一个错误:
TypeError:require(...)不是函数 我可以看到pg-promise有一个带参数的函数(第二个括号),但不知道如何模拟这个?

1 个答案:

答案 0 :(得分:0)

对于其他人不太确定如何做到这一点:

const fakeDB = {
  one: jest.fn()
}

function fakePgpFunc() {
  return fakeDB
}
fakePgpFunc.end = jest.fn()

jest.doMock("pg-promise", () => {
  return jest.fn(() => fakePgpFunc)
})

const insertStuff = require("../src/db-utils").insertStuff

beforeEach(() => {
  jest.clearAllMocks()
})

test("params for inserting stuff are correct", done => {
  fakeDB.one.mockImplementationOnce(() => {
    return Promise.resolve({"stuff": "Stuff", "id": 123456789})
  })

  insertStuff("Stuff").then((data) => {
    expect(fakeDB.one).toHaveBeenCalledTimes(1)
    const insertStuffCall = fakeDB.one.mock.calls[0]
    expect(insertStuffCall[0]).toEqual("INSERT INTO test(stuff) VALUES ($1) RETURNING id, stuff")
    expect(queryInsertCall[1]).toEqual(["Stuff"])
    expect(data).toEqual({id: 123456789, stuff: "Stuff"})
    expect(fakePgpFunc.end).toHaveBeenCalledTimes(1)
    done()
  })
})
相关问题