“And We made the qiblah (prayer direction towards Jerusalem) which you used to face, only to test those who followed the Messenger (Muhammad (صلى الله عليه وسلم)) from those who would turn on their heels (i.e. disobey the Messenger (صلى الله عليه وسلم).” (Al-Baqarah, 2:143)
Imām Muḥammad Amin al-Shanqiṭi comments:
An ignorant person may surmise that the apparent meaning of this verse implies that the Most High gains knowledge from this test that He was not previously aware of. Glorified and high be He above such great falsehood. Rather, He—the Most High—knows the occurrence of all events before they occur. The fact of Him testing his slaves does not represent the gaining of knowledge that He did not previously possess. This has been explicitly stated in His—the Exalted, the Most High’s—saying:
“But that Allah might test what is in your breasts; and to maḥis [purify] that which was in your hearts (sins). And Allah is All-Knower of what is in (your) breasts.” (Ali-ʿImran, 3:154)
His saying “test” here proves that He does not gain awareness of knowledge from this test which He did not previously know. Glorified and high be He above such great falsehood. This is because the One who is the All-Knower of what is in the breasts is above needing to test [for the purpose of making himself aware].
Therefore, the meaning of “only to test” in the verse is meant to grant knowledge that stipulates either reward or punishment. This does not contradict Him being the All-Knower before this. The benefit of testing people is exposing their matter to mankind. As for the One who knows all secrets and private conversations, He is knowledgeable of everything that shall occur, which is plainly evident.