Jest API class using axios returning undefined

I have a react and typescript class containing reusable API calls set up using axios to be imported and utilised to interact with a REST endpoint:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export default class NetworkConfigService {
private authService: AuthService;
private networkId: string | null;
private axiosInstance: AxiosInstance;
constructor() {
this.authService = new AuthService();
this.networkId = localStorage.getItem("selectedNetworkCode");
const headers: AxiosRequestConfig = {
headers: {
"Content-Type": "application/json",
accept: "application/json, text/plain, */*"
},
responseType: "json"
};
this.axiosInstance = axios.create({
baseURL: config.NetworkConfigEndpoint,
...headers
});
this.axiosInstance.interceptors.request.use(async (config) => {
try {
const token = await this.authService.getAccessToken();
config.headers["Authorization"] = `Bearer ${token}`;
return config;
} catch (error) {
throw error;
}
});
}
public async getAllNetworkEntities(): Promise<[{ utc_data: UtcData }]> {
try {
const response = await this.axiosInstance.get<
[{ utcData: UtcData }]
>("/api/Configurations/networks", {
params: {
networkIDs: this.networkId
}
});
const responseData = response.data;
return responseData;
} catch (error) {
throw error;
}
}
public async getPlansForParent(
parent: EntityType,
parentName: string
): Promise<Plan[]> {
try {
const response = await this.axiosInstance.get<Plan[]>(
`/api/Configurations/${this.networkId}/plans/${parent}/${parentName}`
);
const responseData = response.data;
return responseData;
} catch (error) {
throw error;
}
}
}
</code>
<code>export default class NetworkConfigService { private authService: AuthService; private networkId: string | null; private axiosInstance: AxiosInstance; constructor() { this.authService = new AuthService(); this.networkId = localStorage.getItem("selectedNetworkCode"); const headers: AxiosRequestConfig = { headers: { "Content-Type": "application/json", accept: "application/json, text/plain, */*" }, responseType: "json" }; this.axiosInstance = axios.create({ baseURL: config.NetworkConfigEndpoint, ...headers }); this.axiosInstance.interceptors.request.use(async (config) => { try { const token = await this.authService.getAccessToken(); config.headers["Authorization"] = `Bearer ${token}`; return config; } catch (error) { throw error; } }); } public async getAllNetworkEntities(): Promise<[{ utc_data: UtcData }]> { try { const response = await this.axiosInstance.get< [{ utcData: UtcData }] >("/api/Configurations/networks", { params: { networkIDs: this.networkId } }); const responseData = response.data; return responseData; } catch (error) { throw error; } } public async getPlansForParent( parent: EntityType, parentName: string ): Promise<Plan[]> { try { const response = await this.axiosInstance.get<Plan[]>( `/api/Configurations/${this.networkId}/plans/${parent}/${parentName}` ); const responseData = response.data; return responseData; } catch (error) { throw error; } } } </code>
export default class NetworkConfigService {
    private authService: AuthService;
    private networkId: string | null;
    private axiosInstance: AxiosInstance;

    constructor() {
        this.authService = new AuthService();
        this.networkId = localStorage.getItem("selectedNetworkCode");

        const headers: AxiosRequestConfig = {
            headers: {
                "Content-Type": "application/json",
                accept: "application/json, text/plain, */*"
            },
            responseType: "json"
        };

        this.axiosInstance = axios.create({
            baseURL: config.NetworkConfigEndpoint,
            ...headers
        });

        this.axiosInstance.interceptors.request.use(async (config) => {
            try {
                const token = await this.authService.getAccessToken();
                config.headers["Authorization"] = `Bearer ${token}`;
                return config;
            } catch (error) {
                throw error;
            }
        });
    }

    public async getAllNetworkEntities(): Promise<[{ utc_data: UtcData }]> {
        try {
            const response = await this.axiosInstance.get<
                [{ utcData: UtcData }]
            >("/api/Configurations/networks", {
                params: {
                    networkIDs: this.networkId
                }
            });
            const responseData = response.data;
            return responseData;
        } catch (error) {
            throw error;
        }
    }

    public async getPlansForParent(
        parent: EntityType,
        parentName: string
    ): Promise<Plan[]> {
        try {
            const response = await this.axiosInstance.get<Plan[]>(
                `/api/Configurations/${this.networkId}/plans/${parent}/${parentName}`
            );
            const responseData = response.data;
            return responseData;
        } catch (error) {
            throw error;
        }
    }
}

This is imported into a component and defined, the function is then called in a useEffect to ensure data is fetched upon the mounting of a component:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const networkConfigService = useMemo(() => new NetworkConfigService(), []);
const fetchData = useCallback(async () => {
try {
const allNetworkItems = await networkConfigService.getAllNetworkEntities();
console.log(allNetworkItems);
if (allNetworkItems) {
dispatch(addEntityData({ utc_data: allNetworkItems[0].utc_data }));
}
} catch (error) {
console.error("Error fetching data:", error);
}
}, [networkConfigService, dispatch]);
useEffect(() => {
fetchData();
}, [fetchData]);
</code>
<code>const networkConfigService = useMemo(() => new NetworkConfigService(), []); const fetchData = useCallback(async () => { try { const allNetworkItems = await networkConfigService.getAllNetworkEntities(); console.log(allNetworkItems); if (allNetworkItems) { dispatch(addEntityData({ utc_data: allNetworkItems[0].utc_data })); } } catch (error) { console.error("Error fetching data:", error); } }, [networkConfigService, dispatch]); useEffect(() => { fetchData(); }, [fetchData]); </code>
const networkConfigService = useMemo(() => new NetworkConfigService(), []);

    const fetchData = useCallback(async () => {
        try {
            const allNetworkItems = await networkConfigService.getAllNetworkEntities();
            console.log(allNetworkItems);
            if (allNetworkItems) {
                dispatch(addEntityData({ utc_data: allNetworkItems[0].utc_data }));
            }
        } catch (error) {
            console.error("Error fetching data:", error);
        }
    }, [networkConfigService, dispatch]);
    
    useEffect(() => {
        fetchData();
    }, [fetchData]);

Similarly the plansforParent is called in a method within the component to fetch the relevant plans based on a parent selection:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const handleSearchFieldSelection = async (selectedEquipment: Equipment) => {
formik.setFieldValue("selectedEquipment.name", selectedEquipment.name);
formik.setFieldValue("selectedEquipment.description", selectedEquipment.description);
formik.setFieldValue("selectedEquipment.alternativeName", selectedEquipment.alternativeName);
setAction((prevAction) => {
return {
...prevAction,
switchPlan: {
...prevAction,
selectedEquipment: selectedEquipment
}
};
});
const plans = await networkConfigService.getPlansForParent(formik.values.entityType, selectedEquipment.name);
const newPlans = plans ? plans : [];
setPlans(newPlans);
};
</code>
<code>const handleSearchFieldSelection = async (selectedEquipment: Equipment) => { formik.setFieldValue("selectedEquipment.name", selectedEquipment.name); formik.setFieldValue("selectedEquipment.description", selectedEquipment.description); formik.setFieldValue("selectedEquipment.alternativeName", selectedEquipment.alternativeName); setAction((prevAction) => { return { ...prevAction, switchPlan: { ...prevAction, selectedEquipment: selectedEquipment } }; }); const plans = await networkConfigService.getPlansForParent(formik.values.entityType, selectedEquipment.name); const newPlans = plans ? plans : []; setPlans(newPlans); }; </code>
const handleSearchFieldSelection = async (selectedEquipment: Equipment) => {
        formik.setFieldValue("selectedEquipment.name", selectedEquipment.name);
        formik.setFieldValue("selectedEquipment.description", selectedEquipment.description);
        formik.setFieldValue("selectedEquipment.alternativeName", selectedEquipment.alternativeName);

        setAction((prevAction) => {
            return {
                ...prevAction,
                switchPlan: {
                    ...prevAction,
                    selectedEquipment: selectedEquipment
                }
            };
        });
        const plans = await networkConfigService.getPlansForParent(formik.values.entityType, selectedEquipment.name);
        const newPlans = plans ? plans : [];
        setPlans(newPlans);
    };

In the test file I have mocked the route to the class containing the API methods and axios:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>jest.mock("../../../../../../API/NetworkConfig/NetworkConfig.service");
jest.mock("axios");
const axios = require("axios");
let netWorkConfigService = new NetworkConfigService();
</code>
<code>jest.mock("../../../../../../API/NetworkConfig/NetworkConfig.service"); jest.mock("axios"); const axios = require("axios"); let netWorkConfigService = new NetworkConfigService(); </code>
jest.mock("../../../../../../API/NetworkConfig/NetworkConfig.service");
jest.mock("axios");
const axios = require("axios");
let netWorkConfigService = new NetworkConfigService();

I’ve tried setting up a beforeEach to fetch data initially I tried mocking axios and its response but the console.log in useEffect came back undefined.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>beforeEach(() => {
const utc: { utc_data: UtcData }[] = [];
const resp = { data: utc };
axios.get.mockImplementation(() => Promise.resolve(resp));
});
</code>
<code>beforeEach(() => { const utc: { utc_data: UtcData }[] = []; const resp = { data: utc }; axios.get.mockImplementation(() => Promise.resolve(resp)); }); </code>
beforeEach(() => {
        const utc: { utc_data: UtcData }[] = [];

        const resp = { data: utc };
        axios.get.mockImplementation(() => Promise.resolve(resp));
    });

As that failed I then tried using a jest spy to intercept API calls to the networkConfigService and method but the data still returns undefined.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> beforeAll(() => {
let netWorkConfigService = new NetworkConfigService();
const mockGetAllNetworkEntities = jest.spyOn(netWorkConfigService, "getAllNetworkEntities");
mockGetAllNetworkEntities.mockResolvedValue([]);
});
</code>
<code> beforeAll(() => { let netWorkConfigService = new NetworkConfigService(); const mockGetAllNetworkEntities = jest.spyOn(netWorkConfigService, "getAllNetworkEntities"); mockGetAllNetworkEntities.mockResolvedValue([]); }); </code>
 beforeAll(() => {
        let netWorkConfigService = new NetworkConfigService();
        const mockGetAllNetworkEntities = jest.spyOn(netWorkConfigService, "getAllNetworkEntities");
        mockGetAllNetworkEntities.mockResolvedValue([]);
    });

This is a similar case for the API call for handleSearchFieldSelection() method which should call networkConfigService.getPlansForParent(formik.values.entityType, selectedEquipment.name) it returns undefined and hence the last part of my test:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>await user.click(selectPlanId[3]);
const option = screen.getAllByRole("option");
</code>
<code>await user.click(selectPlanId[3]); const option = screen.getAllByRole("option"); </code>
await user.click(selectPlanId[3]);
const option = screen.getAllByRole("option");

Fails as no option roles populate for planId due to the undefined response and consequently there is nothing to select.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>it("selects all dropdowns and submits the form", async () => {
const user = userEvent.setup();
renderComponent();
const selectEntityType = screen.getAllByRole("combobox");
const entityTypeSelect = screen.getByTestId("entityType");
expect(selectEntityType[0]).toBeInTheDocument();
await user.click(selectEntityType[0]);
const optionToSelect = screen.getByText("EntityType.Scoot_Region");
await user.click(optionToSelect);
expect(entityTypeSelect).toHaveValue("Region");
const autocomplete = screen.getAllByRole("combobox");
await userEvent.type(autocomplete[1], "{arrowdown}{enter}");
expect(autocomplete[1]).toHaveValue("TestName-AltName, Test Description");
const selectPlanType = screen.getAllByRole("combobox");
const planTypeSelect = screen.getByTestId("planTypeSelect");
expect(planTypeSelect).toBeInTheDocument();
await user.click(selectPlanType[2]);
const optionToSelect2 = screen.getByText("PlanTypes.LocalControl");
await user.click(optionToSelect2);
expect(planTypeSelect).toHaveValue("LocalControl");
const selectPlanId = screen.getAllByRole("combobox");
const planIdSelect = screen.getByTestId("planIdSelect");
expect(planIdSelect).toBeInTheDocument();
await user.click(selectPlanId[3]);
const option = screen.getAllByRole("option");
await user.click(option[0]);
const submitButton = screen.getByText("StrategyManager.Save_Action");
await user.click(submitButton);
expect(mockHandleSubmit).toHaveBeenCalled();
});
</code>
<code>it("selects all dropdowns and submits the form", async () => { const user = userEvent.setup(); renderComponent(); const selectEntityType = screen.getAllByRole("combobox"); const entityTypeSelect = screen.getByTestId("entityType"); expect(selectEntityType[0]).toBeInTheDocument(); await user.click(selectEntityType[0]); const optionToSelect = screen.getByText("EntityType.Scoot_Region"); await user.click(optionToSelect); expect(entityTypeSelect).toHaveValue("Region"); const autocomplete = screen.getAllByRole("combobox"); await userEvent.type(autocomplete[1], "{arrowdown}{enter}"); expect(autocomplete[1]).toHaveValue("TestName-AltName, Test Description"); const selectPlanType = screen.getAllByRole("combobox"); const planTypeSelect = screen.getByTestId("planTypeSelect"); expect(planTypeSelect).toBeInTheDocument(); await user.click(selectPlanType[2]); const optionToSelect2 = screen.getByText("PlanTypes.LocalControl"); await user.click(optionToSelect2); expect(planTypeSelect).toHaveValue("LocalControl"); const selectPlanId = screen.getAllByRole("combobox"); const planIdSelect = screen.getByTestId("planIdSelect"); expect(planIdSelect).toBeInTheDocument(); await user.click(selectPlanId[3]); const option = screen.getAllByRole("option"); await user.click(option[0]); const submitButton = screen.getByText("StrategyManager.Save_Action"); await user.click(submitButton); expect(mockHandleSubmit).toHaveBeenCalled(); }); </code>
it("selects all dropdowns and submits the form", async () => {
        const user = userEvent.setup();
        renderComponent();

        const selectEntityType = screen.getAllByRole("combobox");
        const entityTypeSelect = screen.getByTestId("entityType");
        expect(selectEntityType[0]).toBeInTheDocument();
        await user.click(selectEntityType[0]);
        const optionToSelect = screen.getByText("EntityType.Scoot_Region");
        await user.click(optionToSelect);
        expect(entityTypeSelect).toHaveValue("Region");

        const autocomplete = screen.getAllByRole("combobox");
        await userEvent.type(autocomplete[1], "{arrowdown}{enter}");
        expect(autocomplete[1]).toHaveValue("TestName-AltName, Test Description");

        const selectPlanType = screen.getAllByRole("combobox");
        const planTypeSelect = screen.getByTestId("planTypeSelect");
        expect(planTypeSelect).toBeInTheDocument();
        await user.click(selectPlanType[2]);
        const optionToSelect2 = screen.getByText("PlanTypes.LocalControl");
        await user.click(optionToSelect2);
        expect(planTypeSelect).toHaveValue("LocalControl");

        const selectPlanId = screen.getAllByRole("combobox");
        const planIdSelect = screen.getByTestId("planIdSelect");
        expect(planIdSelect).toBeInTheDocument();
        await user.click(selectPlanId[3]);
        const option = screen.getAllByRole("option");
        await user.click(option[0]);

        const submitButton = screen.getByText("StrategyManager.Save_Action");
        await user.click(submitButton);
        expect(mockHandleSubmit).toHaveBeenCalled();
    });

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật