I created a function that connects to an API and returns a promise.. I wanted to test that function so created a mock function in Jest to handle it, however I am not really sure I am doing this right and I am finding it very hard to find good resources on how to go about writing good unit tests..
export const sbConnect = (userId) => {
return new Promise((resolve, reject) => {
const sb = new SendBird({appId: APP_ID});
sb.connect(userId, API_Token, (user, error) => {
if (error) {
reject(error);
} else {
resolve(user);
}
});
});
};
This is the function I am trying to test. I have created a test and tried this so far..
import {sbConnect} from '../helpers/sendBirdSetupActions';
const SendBird = jest.fn();
describe('Connects to SendBird API', () => {
it('Creates a new SB instance', () => {
let userId = 'testUser';
let APP_ID = 'Testing_App_ID_001';
sbConnect(userId);
expect(SendBird).toBeCalled();
});
});
You can use jest.mock(moduleName, factory, options) to mock
sendbird
module manually.Mock
SendBird
constructor, instance, and its methods.E.g.
index.ts
:index.test.ts
:unit test result:
source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/65220363