sklearn KNN imputation
The short answer is that usually if you are performing data transforms, you fit on the training data and transform training and test data.
The long answer is that if you are doing purely supervised machine learning then you want to avoid &quot;leakage&quot;.

Data leakage is when information from outside the training dataset is used to create the model.


https://machinelearningmastery.com/data-leakage-machine-learning/

I'd read the above link if you want more information. In your case, it just comes down to preprocessing only using information in your training data.