I have a simple login api call where the base url is in config file, code below
api.js
export const login = (username, password) => {
Axios.post(`${config.loginApi.baseUrl}/login`, {
username,
password
})
.then(res => res)
.catch(e => e);
};
I wrote the test case(s) below,
api.test.js
import axios from 'axios';
import { login } from './api';
import MockAdapter from 'axios-mock-adapter';
import config from 'config';
describe('signin signup Api', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('logs in successfully', (done) => {
const mock = new MockAdapter(axios);
mock.onGet(`${config.loginApi.baseUrl}/login`).reply(200, { data: '1234abcd' });
login('[email protected]', 'test').then((res)=>{
expect(res).toEqual('1234abcd');
done();
});
});
or the other test case I wrote earlier
import axios from 'axios';
import { login } from './api';
import config from 'config';
jest.mock('axios');
it('logs in successfully', async () => {
axios.post.mockImplementationOnce(() => Promise.resolve({ data: '1234abcd' }));
await expect(login('[email protected]', 'test')).resolves.toEqual('1234abcd');
});
I researched and found this post close to my issue. But in all the cases I'm getting TypeError: Cannot read property 'baseUrl' of undefined
Why is this not able to know the baseUrl?
I tried mocking the config,
jest.mock(config);
got TypeError: moduleName.split is not a function.
Please suggest a fix/workaround.
Adding more info on the config
in config folder, I have
require('dotenv').config();
module.exports = config;
in development environment, it will pick this config from dev.js, in prod - prod.js and so on
in public folder, dev.js file I have
loginApi: {
baseUrl: 'https://abcd.com',
mocks: true,
mockDelay: 2000
}
I found the fix for this issue,
in the setupTests.js, I added
This fixed that TypeError: Cannot read property 'baseUrl' of undefined issue.