import request from "supertest";
import getConfig from "../../libs/config";
import getApp from '../../app'
import axios from "axios";

jest.mock('axios')

beforeAll(done => {
    done()
  })

describe("form post with middleware on eaach postrequest", () => {
    test('when no postcode is  entered in form should redirect to error page', async ()=>{
      const config = getConfig();
      const app = getApp(config);
  
        const appRequest = request(app);   
        const response = await appRequest.post('/postcode').send({postcode: ''});
        expect(response.status).toBe(302);
        expect(response.text).toContain('Redirecting to /postcode?hasError=true')
    });

    test('when incorrect postcode is  entered in form should redirect to error page', async ()=>{
        const config = getConfig();
        const app = getApp(config);
    
          const appRequest = request(app);   
          const response = await appRequest.post('/postcode').send({postcode: 'a2345fd'});
          expect(response.status).toBe(302);
          expect(response.text).toContain('Redirecting to /postcode?hasError=true')
      });

      test('when correct postcode is entered in form should not redirect to error page', async ()=>{
        const config = getConfig();
        const app = getApp(config); 
        const appRequest = request(app); 
        const testData = [{
            "UPRN": "100110668168",
            "AddressLine1": "1 Mitford Gardens - Ineligible",
            "AddressLine2": "",
            "AddressLine3": "",
            "Town": "Stakeford, Choppington",
            "County": "Northumberland",
            "Postcode": "NE62 5YR"
        }];
        (axios.get as jest.Mock).mockResolvedValueOnce({status: 200, data: testData})
            
          const res = await appRequest.post('/postcode').send({postcode: 'ne128rf'});
          expect(res.status).toBe(302);
          expect(res.header['location']).toContain('/address-select');
      })
})