简体   繁体   English

如何使用笑话功能发送响应? 它给出了异步回调错误

[英]How to send response using jest function? It gives async callback error

I try to mock model response using jest. 我尝试使用玩笑来模拟模型响应。 It will go in my jest.mock.createMondayBox function and it can print "hello world", which means it can really go inside mock model that replaces the original model. 它将进入我的jest.mock.createMondayBox函数中,并且可以显示“ hello world”,这意味着它可以真正进入替换原始模型的模拟模型中。

models/mondayModel.js 车型/ mondayModel.js

var mondayModel = function() {
  function createBox (req, payload, callback) { 
   ...
   boxClient.request(req, {
     method: 'POST'
     path:
     body: 
     headers: { }
   }, function(error, response) {
      if(error || (response.statusCode && response.statusCode !== 200)) { 
        return callback(new ErrorObject({
           errorName:'createBoxFailure', 
           errorMessage: 'Error in creating box'
        })
      }
      return callback(null, {resultSet: response.body})
   })

  }
  function fnB (req, callback) { }
  function fnC (req, callback) { }
  function fnD (req, callback) { }
  return {
    createBox: createBox,
    fnB: fnB,
    fnC: fnC,
    fnD: fnD
  }
}

module.exports = mondayModel

controller/boxController.js 控制器/ boxController.js

var MondayModel = require('../models/mondayModel');


function createMondayBox(req, res, next) {
   ...
   var mondayModel = new MondayModel();
   mondayModel.createBox(req, payload, function(error, result) {

      if(error) {
         res.json({'status': 'BADREQUEST', 'statusCode': 400})

      } else {
         var mondaybox = result.resultSet.mondayboxes && result.resultSet.mondayboxes[0]

         var mappedResponse = Response.mapCreateMondaybox(req, resultSet);
         utils.logKK(req, utils.getKK(mappedResponse.mondayboxes[0]))
         res.json(mappedResponse);
      }

   ...
   }
}

boxController-test.jest boxController-test.jest


let boxController = null

describe('money tracker', () => {
    beforeAll(() => {        
        jest.mock('../../../../models/mondayBox',
            () => function mondayBoxModel() {
               console.log("hello world")
               return {
                createBox: (req, payload, callback) => {
                  return callback(null, {
                        resultSet: {
                            mondayboxes: [{ name: '1' }, { name: '2' }]
                        },
                        json: jest.fn()
                    })}
                fnB: jest.fn(),
                fnC: jest.fn(),
                fnD: jest.fn()
                }
               }
        }))    
    )
        boxController = require('../controllers/boxController')
    })

    test('success case', done => {
       const req = {}
       const res = new Promise(r =>
         r({ json: jest.fn(), status: jest.fn() })
       )
       mondayBoxController.createMondayBox(req, res, (cbErr, cbRes) => {
          expect(res.json).toBeCalled();
          done()
       }) 
    }
}

TypeError: res.json is not a function TypeError:res.json不是函数

May I know how to solve this problem? 我可以知道如何解决这个问题吗? How to write mock model response? 如何编写模拟模型响应? Thanks 谢谢

First of all you need to test the controller only, hence you should do 首先,您只需要测试控制器,因此您应该

Update the controller to 将控制器更新为

var MondayModel = require('../models/mondayModel');


function createMondayBox(req, res, next) {
 ...
 var mondayModel = new MondayModel();
 mondayModel.createBox(req, payload, function(error, result) {

   if(error) {
     res.json({'status': 'BADREQUEST', 'statusCode': 400})

   } else {
     var mondaybox = result.resultSet.mondayboxes && 
     result.resultSet.mondayboxes[0]

     var mappedResponse = Response.mapCreateMondaybox(req, resultSet);
     utils.logKK(req, utils.getKK(mappedResponse.mondayboxes[0]))
     res.json(mappedResponse);
     next();
   }

  ...
 }
}

And in test file: 并在测试文件中:

import {createRequest, createResponse}  from 'node-mocks-http'
import boxController from 'controller/boxController.js'
import mondayBoxModal from 'models/mondayBox';

jest.mock('models/mondayBox', () => () => ({ createBox: (req, payload, cb) => cb(null, { resultSet: { mondayboxes: ['resultsData']} } }));

describe('money tracker', () => {
 let req;
 let res;
 let next = jest.fn;
 beforeEach(() => {
    jest.clearAllMocks();
    req  = createRequest({
      method: 'GET',
      url: '/user/42',
      params: {
       id: 42
      }
    });

    res = httpMocks.createResponse();
    res.json = jest.fn;

 })

 test('success case', done => {
   const req = {}

   mondayBoxController.createMondayBox(req, res, (cbErr, cbRes) => {
      expect(res.json).toBeCalled();
      done()
   })
}

} }

Your function transfer(req, res, next) takes 3 argument and would use res.json() while your call boxController.transfer(req, {}, fn) is passing an empty object. 您的函数transfer(req, res, next)接受3个参数,并在调用boxController.transfer(req, {}, fn)传递空对象时使用res.json() It probably fails silently here. 它可能在这里无声地失败了。

And transfer didn't call next at all in your sample. 在您的样本中, transfer根本没有调用。

Please make sure your example resembles the actual code accurately. 请确保您的示例准确地类似于实际代码。

Update 更新

It has nothing to do with async or not 它与异步无关

if you write this 如果你写这个

const res = new Promise(r =>
  r({ json: jest.fn(), status: jest.fn() })
)
mondayBoxController.createMondayBox(req, res, (cbErr, cbRes) => {
  expect(res.json).toBeCalled();
  done();
})

then 然后

mondayModel.createBox(req, payload, function (error, result) {
  console.log(res); // Promise, which has no json method
  console.log(res.json); // undefined
  // but
  console.log(await res); // the desired mocked res obj
  // btw this is incorrect usage of await
  if (error) {
    res.json();
  } else {
    ...
  }
});

res in mondayModel.createBox 's callback is exactly what you passed into mondayBoxController.createMondayBox(req, res, handler) . mondayModel.createBox的回调中的res就是您传递给mondayBoxController.createMondayBox(req, res, handler)

instead, do this 相反,这样做

const res = {
  json: jest.fn(); // or whatever behaviour you desire
};
mondayBoxController.createMondayBox(req, res, handler);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM