简体   繁体   中英

React Jest TypeError: Cannot read property 'baseUrl' of undefined

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('dee@gmail.com', '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('dee@gmail.com', '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

global.config ={
   loginApi: {
        baseUrl: 'https://abcd.com',
        mocks: true,
        mockDelay: 2000
    } 
}

This fixed that TypeError: Cannot read property 'baseUrl' of undefined issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM