1

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.
})
2
  • It's unclear what's going on. Why should a be called? You're not calling it. Commented Feb 2, 2019 at 10:33
  • then how can i know that b will be called. Check the orginal snippet it will give you better view github.com/winstonjs/winston#formats. here if we need a customFormat we can give that but customFormat is not a function it is just a variable. Since i was not able to test it i moved out the customFormat and made it as a functon tried to test it. But it is not working Commented Feb 2, 2019 at 10:37

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

12 Comments

i have already mocked the entire winston library with jest.genMockFromModule('winston');
i tried the code but it is not covering the line, still the lines are uncovered
I don't think that genMockFromModule will generate nested aa object.. You may also need to test a callback, like const cb = bMock.calls[0][1]; expect(cb({ message: ... })).toBe(...);
i didn't understand can you update the answer snippet
i have posted the entire code , can you check this one stackoverflow.com/questions/54502290/… and suggest a solution
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.