簡體   English   中英

如何模擬帶有參數的模塊

[英]how to mock a module that takes a parameter

我正在嘗試為使用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有一個帶有參數的函數(第二個括號),但是不確定現在如何模擬它?

對於其他人,不太確定如何執行此操作:

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()
  })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM