I've done something similar nearly two years ago[1]. The problem is rather difficult, especially with all the JavaScript frameworks in existence right now. I've tried to build a state machine for handling those frameworks but never got around to finishing it. There's basically and endless amount of combinations one can do, thus you probably want to limit depth or something. You also have to be able to detect ::after and similar kind of selectors, which isn't always straightforward with querySelector and needs quite a bit of cleaning. I ran into a few other (edge) cases, which I cannot remember right now.
Nonetheless, it is a challenging and fun problem to solve.
My naive opinion is that this should be done by the browser, perhaps in the developer tools. You would be marking a session as "integration tests" and at the end it would give you a simplified css file without the unused rules during testing.
Nonetheless, it is a challenging and fun problem to solve.
[1]: https://github.com/Kevin-A/css-detector