Write integration test for rest_pre_serve_request

The question actually has nothing specific to wordpress, but maybe it is worth answering.

There is simply no code of your own in that sample that can be/is worth testing, therefor there isn’t much to unit test.

Lets look at the details. add_filter is integration with core code, remove_filter is integration with core code and header is integration with PHP core. If you remove all of those lines you are left with zero code.

Or to say it differently, the three functions mentions above are changing the global state and not your internal state, and while you might be able to construct a relevant test, in the end you are going to be testing them much more than testing your own code.

What you need here is an integration test, set a wordpress instance with your code, send an api request and inspect the result.