|
1 | 1 | import React from 'react'; |
2 | | -import 'jest-styled-components'; |
3 | | - |
4 | | -import renderWithTheme from '../../../hoc/shallowWithTheme'; |
| 2 | +import { fireEvent, render } from '@testing-library/react'; |
5 | 3 | import PostcodeLookup from './PostcodeLookup'; |
6 | 4 |
|
7 | | -it('renders correctly', () => { |
8 | | - const tree = renderWithTheme( |
9 | | - <PostcodeLookup onSelect={address => alert(JSON.stringify(address, null, 2))} /> |
10 | | - ).toJSON(); |
11 | | - expect(tree).toMatchSnapshot() |
| 5 | +// Mock the fetch function |
| 6 | +global.fetch = jest.fn(() => |
| 7 | + Promise.resolve({ |
| 8 | + ok: true, |
| 9 | + json: () => |
| 10 | + Promise.resolve({ |
| 11 | + addresses: [ |
| 12 | + { |
| 13 | + address_id: 66743883, |
| 14 | + Line1: '77 CARLYLE ROAD', |
| 15 | + posttown: 'BRISTOL', |
| 16 | + postcode: 'BS5 6HQ' |
| 17 | + } |
| 18 | + ] |
| 19 | + }) |
| 20 | + }) |
| 21 | +); |
| 22 | + |
| 23 | +// Mock the alert function |
| 24 | +global.alert = jest.fn(); |
| 25 | + |
| 26 | +describe('PostcodeLookup', () => { |
| 27 | + it('should trigger an alert with the address when given postcode bs5 6hq', async () => { |
| 28 | + const { getByPlaceholderText, getByText } = render( |
| 29 | + <PostcodeLookup |
| 30 | + onSelect={address => alert(JSON.stringify(address, null, 2))} |
| 31 | + /> |
| 32 | + ); |
| 33 | + |
| 34 | + const postcodeInput = getByPlaceholderText('Enter postcode...'); |
| 35 | + fireEvent.change(postcodeInput, { target: { value: 'bs5 6hq' } }); |
| 36 | + |
| 37 | + const findAddressButton = getByText('Find address'); |
| 38 | + fireEvent.click(findAddressButton); |
| 39 | + |
| 40 | + // Wait for the asynchronous operation to complete |
| 41 | + await new Promise(resolve => setTimeout(resolve, 0)); |
| 42 | + |
| 43 | + // Check if alert was called with the correct address |
| 44 | + expect(global.alert).toHaveBeenCalledWith( |
| 45 | + JSON.stringify( |
| 46 | + { |
| 47 | + address_id: 66743883, |
| 48 | + Line1: '77 CARLYLE ROAD', |
| 49 | + posttown: 'BRISTOL', |
| 50 | + postcode: 'BS5 6HQ' |
| 51 | + }, |
| 52 | + null, |
| 53 | + 2 |
| 54 | + ) |
| 55 | + ); |
| 56 | + }); |
12 | 57 | }); |
| 58 | + |
0 commit comments