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
Post a Comment