testing a function inside another function using j

2019-03-02 11:12发布

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.
})

1条回答
Deceive 欺骗
2楼-- · 2019-03-02 11:47

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');
查看更多
登录 后发表回答