England edge out Pakistan in Test thriller