Skip to main content

Why does my Mock fetch always returns null? (Jest)

I have a simple React component that is calling a local API to get a list of products on component mount. The functionality itself works fine. The app is created by create-react-app. However, I'm also trying to test the fetch function in Jest but my mocked global fetch always returns null. Does anyone have an idea why?

It's like my mocked function never even gets called or isn't in scope of the component logic? However the original global fetch doesn't get called either. Just null is returned.

I've also tried re-writing my fetch to use a .then() follow-up and I've tried using the jest-fetch-mock package but the results are the same. I can call my (real) fetch function from the tests and it returns correctly. Only the mocked fetch is causing problems.

Here is the tutorial I've been following: https://www.leighhalliday.com/mock-fetch-jest

The component:

import React, { useState, useEffect } from 'react';
import Product from './Product';

import './Shop.css';


export async function fetchProducts() {
    try {
        const result = await fetch('http://localhost:8080/products', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        const data = await result.json();
        return data;
    } catch (e) {
        return null;
    } 
}

function Shop() {

    const [products, setProducts] = useState([])

    useEffect(async () => {
        const result = await fetchProducts();
        setProducts(result);
    }, []);

    return (
        <>
            <h2>Shop</h2>
            <ul className='list-reset products-wrapper'>
                {products.map((product) => (
                    <Product
                        key={product.id}
                        {...product} />
                ))}
            </ul>
        </>
    );
}

export default Shop;

The test:

import { render, screen } from '@testing-library/react';
import Shop, { fetchProducts } from './Shop';

// Mocking the fetch function
global.fetch = jest.fn(() => {
    return Promise.resolve({
        json: () => Promise.resolve([
            {
                id: '1',
                productName: 'Banana',
                price: 0.39,
                image: '🍌'
            }
        ])
    })
});

beforeEach(() => {
    fetch.mockClear();
});

test('requests the products on mount', async () => {
    const products = await fetchProducts();
    expect(products).toEqual({
        id: '1',
        productName: 'Banana',
        price: 0.39,
        image: '🍌'
    })
});

Failing test:

 FAIL  src/components/Shop/Shop.test.js
  ● requests the products on mount

    expect(received).toEqual(expected) // deep equality

    Expected: {"id": "1", "image": "🍌", "price": 0.39, "productName": "Banana"}
    Received: null

If I log out the mocked fetch method as the test is running it logs the Jest mock:

[Function: mockConstructor] {
        _isMockFunction: true,
        getMockImplementation: [Function],
        mock: [Getter/Setter],
        mockClear: [Function],
        mockReset: [Function],
        mockRestore: [Function],
        mockReturnValueOnce: [Function],
        mockResolvedValueOnce: [Function],
        mockRejectedValueOnce: [Function],
        mockReturnValue: [Function],
        mockResolvedValue: [Function],
        mockRejectedValue: [Function],
        mockImplementationOnce: [Function],
        mockImplementation: [Function],
        mockReturnThis: [Function],
        mockName: [Function],
        getMockName: [Function]
      }
Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Comments

Popular posts from this blog

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console

How to split a rinex file if I need 24 hours data

Trying to divide rinex file using the command gfzrnx but getting this error. While doing that getting this error msg 'gfzrnx' is not recognized as an internal or external command Trying to split rinex file using the command gfzrnx. also install'gfzrnx'. my doubt is I need to run this program in 'gfzrnx' or in 'cmdprompt'. I am expecting a rinex file with 24 hrs or 1 day data.I Have 48 hrs data in RINEX format. Please help me to solve this issue. source https://stackoverflow.com/questions/75385367/how-to-split-a-rinex-file-if-i-need-24-hours-data