javascript - 如何模拟内部函数?

标签 javascript node.js unit-testing mocking jestjs

目前正在写代码测试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/

相关文章:

javascript - Requirejs 优化器 - 为站点的各个部分创建最小的脚本分组

javascript - 使用 node.js 嵌套模块

node.js - 如何优先考虑快速请求/响应而不是其他密集的服务器相关任务

javascript - fatal error : Reached heap limit Allocation failed - JavaScript heap out of memory

delphi - 如何在delphi单元测试中使用可视化组件?

c++ - 是否可以使用 Google Mock (gmock) 捕获参数?

javascript - ASP.Net - 在错误页面上隐藏子菜单

javascript - 页面刷新时加载数据 - dataTable

javascript - Velocity.js 的性能非常低

javascript - 为了更好地进行单元测试,静态类型 javascript 的示例是什么?