使用jest测试另一个函数内的函数 [英] testing a function inside another function using jest

查看:601
本文介绍了使用jest测试另一个函数内的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用jest测试以下代码段。我正在尝试测试winston自定义格式 printf

how can i test the below snippet using jest. I am trying to test the winston custom format the printf

// sample.js

import {aa:{b}} = require("thirparty-package")

const a = () => {
   return b((log) => {
     return `log message will be ${log.message}`
   })
}

module.exports = {
  a
}


// sample.test.js
const customFunctions = require('./sample')

test('should check b function is called and returns a string', () => {
   expect(customFunctions.a).toHaveBeenCalled() // throwing error 
    //jest.fn() value must be a mock function or spy.
})


推荐答案

如果 b 需要进行测试,那么它应该是间谍,而不是 a

If it's b that needs to be tested then it should be a spy, not a.

应该模拟第三方模块(演示):

Third-party module should be mocked (a demo):

const bMock = jest.fn();
jest.mock('thirparty-package', () => ({ aa: { b: bMock } }));
const { a } = require('./sample');
a();
const callback = bMock.mock.calls[0][0]; 
expect(callback).toEqual(expect.any(Function));
expect(callback({ message: 'foo' })).toBe('log message will be foo');

这篇关于使用jest测试另一个函数内的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆