Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeError: Cannot read properties of undefined (reading 'data') #15028

Open
moezbenrebah opened this issue Apr 14, 2024 · 0 comments
Open

TypeError: Cannot read properties of undefined (reading 'data') #15028

moezbenrebah opened this issue Apr 14, 2024 · 0 comments

Comments

@moezbenrebah
Copy link

Version

29

Steps to reproduce

I wrote an unit test to test the below function using axios to fetch data ( I use a json file to mock server request/response):

import axios from 'axios';

export async function updateCountryLanguage(countryName, newLanguage) {
	try {
		const response = await axios(`http://localhost:3000/countries/${countryName}`);

		// console.log('===currentLang===:', response.data.languages) // [ 'Arabic' ]
		const updatedLanguages = [ ...response.data.languages, newLanguage ];

		const updatedResponse = await axios.put(`http://localhost:3000/countries/${countryName}`, {
				...response.data,
				languages: updatedLanguages
		});
		
		console.log('Country language updated successfully:', updatedResponse.data);
	} catch (error) {
			console.error('Error updating country language:', error);
			throw error;
	}
}

updateCountryLanguage('tunisia', 'French')

I function working smoothly and without any error, also the comment log above works fine, but when it come to run the test it always complained about reading undefined from ".data"

test:

import axios from 'axios';
import { updateCountryLanguage } from './A_9';
jest.mock('axios');

describe('updateCountryLanguage', () => {
    it('should add a new language to a country successfully', async () => {
        const countryName = 'Tunisia';
        const newLanguage = 'French';
        axios.get.mockImplementationOnce(() => Promise.resolve({data: {
             languages: ['Arabic']
         }}));
        axios.put.mockResolvedValue({
            data: {
                languages: ['French']
            }
        });

        await updateCountryLanguage(countryName, newLanguage);

        expect(axios.put).toHaveBeenCalledWith(
            `http://localhost:3000/countries/${countryName}`, 
            expect.objectContaining({
                languages: expect.arrayContaining(['Arabic', 'French'])
            })
        );
    });
 });

I don't understand why it failed, and the reason behind

Expected behavior

run test successfully

Actual behavior

Cannot read properties of undefined (reading 'data')

Additional context

No response

Environment

Linux 20.04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant