Facing status code 400 while using React Jest

127 views Asked by At

I am learning unit testing using Jest in React. I want to test status 200 and 400 when my api returns me to reponse. But First one is passing test but second one is facing Request failed with status code 400 error ant then Second case is failed with that. Why am I facing that ? I took a group my cases and I mocked my axios get method with axios-mock-adapter. What is problem do you think. What should I do ? Her is my example code.

UserService.test.ts :

import { ACCOUNT_SETTINGS } from '../../core/constants/apiEndpoints'
import mockServiceInstance from '../__mocks__/MockService'
import { fetchUsersMockData, userClaimsTreeMockData } from "../__mocks__/UserServiceMockData";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";

afterEach(() => {
    jest.clearAllMocks()
});

const mock = new MockAdapter(axios);

// roles/list?PageIndex=0&PageSize=3
describe('fetchAllUsers method', () => {
    let url : string = `${ACCOUNT_SETTINGS.PAGED_LIST}?PageIndex=${0}&PageSize=${3}`;
    
    it("get is succesfull", async () => {
        const mockData = {
            result: fetchUsersMockData,
            error: null,
            isSuccessful: true
        }

        mock.onGet(url).reply(200, mockData);
        const { data } = await axios.get(url)
        expect(data.result).toStrictEqual(fetchUsersMockData);

    })

    it("get has error", async () => {
        mock.onGet(url).reply(400); 
        const { status} = await axios.get(url) // here is error line
    })

})

My example mock data :

fetchUsersMockData = {
    pageIndex: 0,
    pageSize: 3,
    totalCount: 8,
    totalPages: 1,
    items: [
        {
            id: uuidv4(),
            username: "[email protected]",
            name: "Scot",
            surname: "Lawson",
            email: "[email protected]",
            phoneNumber: "03212342345",
            isActive: true,
            isLocked: false,
            timeZone: "Europe/Istanbul"
        }
    ]
}
1

There are 1 answers

0
Vikas On BEST ANSWER

Wrap your error test scenario in try...catch block

Solution:

try {
  it("get has error", async () => {
        mock.onGet(url).reply(400); 
        const { status} = await axios.get(url) // here is error line
    })
}catch(e){
   code///
}

More on Error Handling