目前正在写代码测试controller,需要调用model。为了避免对测试产生副作用,我需要模拟模型。但是,模型的编写方式非常复杂,因为它使用内部函数作为构造函数。我尝试了不同的方法,但仍然没有达到目的。
模型/mondayModel.js
var mondayModel = function() {
function fnA (req, callback) {
...
}
function fnB (req, callback) { }
function fnC (req, callback) { }
function fnD (req, callback) { }
return {
fnA: fnA,
fnB: fnB,
fnC: fnC,
fnD: fnD
}
}
module.exports = mondayModel
Controller /boxController.js
var MondayModel = require('../models/mondayModel');
function transfer(req, res, next) {
...
var mondayModel = new MondayModel();
mondayModel.fnA(req, payload, function(error, result) {
...
}
}
boxController-test.jest
let boxController = null
describe('money tracker', () => {
beforeAll(() => {
jest.mock('../../../../models/mondayBox',
() => ({
mondayBox: {
fnA: jest.fn(),
fnB: jest.fn(),
fnC: jest.fn(),
fnD: jest.fn()
}
}))
)
boxController = require('../controllers/boxController')
})
test('success case', done => {
const req = {}
const payload = {}
boxController.transfer(req, payload, (cbErr, cbRes) => {expect(cbRes).toBe('OK')
}
}
但它给出了 TypeError: mondayModel is not a constructor
我可以知道如何解决这个模拟(内部)函数吗? 谢谢
最佳答案
首先,我认为 jest.mock
应该放在顶部。它会被提升到顶部,但我不知道如果放在另一个函数中会发生什么。
而且,你应该传递一个函数,它返回一个新的
const model = require('../mondayModel');
jest.mock('../../../../models/mondayBox', () => function Model() {
return {
fnA: jest.fn(),
fnB: jest.fn(),
fnC: jest.fn(),
fnD: jest.fn(),
}
});
在你的情况下,
const MondayModel = require('../mondayModel');
var mondayModel = new MondayModel();
本质上是
const MondayModel = {
mondayBox: {
fnA: jest.fn(),
fnB: jest.fn(),
fnC: jest.fn(),
fnD: jest.fn()
},
};
var mondayModel = new MondayModel();
你可以尝试控制台记录一下
关于javascript - 如何模拟内部函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57613136/