Wahab Riaz and Imad Wasim turned around the pressure and dominated Afghanistan in the death overs. Hashmatullah (74 not out) and Rashid Khan (5*) needed four runs from the last over to take their side over the line. Wahab bowled the last over of the Afghanistan innings.
However, Rashid with a double on the second delivery and single on the third ball helped level the scores. Hashmatullah on the fourth ball completed the winning run and celebrated Afghanistan's first warm-up victory by punching in the air.
Mohammad Shahzad and Hazratullah Zazai got off to a brilliant start in a 263 run-chase with an 80-run stand in 11.1 overs, before Shahzad was retired hurt for 23.
Samiullah Shinwari and Mohammad Nabi too contributed with their brief 22 and 34 runs, respectively.
Earlier, lone warrior Babar Azam pushed the scoreboard of Pakistan to 262 all out after the team elected to bat. The right-hander maintained his cool in spite of not finding support on the other end.
Babar took 108 balls to score 112 runs, including 10 boundaries and two sixes, before Rahmat Shah ran to his left from deep backward square to dismiss him off Dawlat Zadran.
Imam-ul-Haq and Fakhar Zaman started the innings on a good note. Just when the duo were about to complete 50-run opening stand, Hamid Hassan bowled Imam with the Pakistan score reading 47.
The first breakthrough energised Afghanistan and in the 12th over Mohammad Nabi bagged two wickets - Fakhar (19) and Haris Sohail cheaply for one. Spin prodigy Rashid Khan did not let Mohammad Hafeez open his arms and sent him back to the pavilion for 12.
Babar and Shoaib Malik formed a 103-run partnership for the fifth wicket, helping Pakistan revive and cross the 200-run mark before Nabi returned to end the innings of Malik for 44.
Sarfaraz Ahmed failed to play a captain's knock and returned after contributing just 13 runs. Babar soon after taking Pakistan to 250-plus run was forced to return and his side folded on 262.
Nabi was the pick of the Afghanistan bowlers as he returned impressive figures of 3/46 off his allotted 10 overs.
Pakistan will next meet Bangladesh on May 26, while Afghanistan will face host England on May 27 in their respective warm-up matches.
Brief scores: Afghanistan 263/7 (Hashmatullah Shahidi 74*, Hazratullah Zazai 49, Wahab Riaz 3-46, Imad Wasim 2-29) beat Pakistan 262 (Babar Azam 112, Shoaib Malik 44, Mohammad Nabi 3-46, Rashid Khan 2-27) by three wickets.