I am having trouble testing and automating conditional matchMedia statements. I would like to create a unit test that can test many widths (in this case desktop and tablet widths).
I can write a test for each device/media query (e.g. this.setForTablet()) but how do I test the below mini controller?
Is there a practical way to test statements such as the following? Is it a better practice to refactor my code to avoid statements such as the following, if so how?
if ( window.matchMedia('(max-width: 768px)').matches ) { // View <= tablet
this.setForTablet();
} else { // View > tablet
this.setForDesktop();
}
Refactor and return.
Refactor the mini controller to accept different input/widths and return known/expected values for each case. These will be your test assertions.
One should expect matchMedia to works as intended and test only the user/coder's own code.