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

查看:28
本文介绍了使用 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天全站免登陆