简体   繁体   中英

Unit testing JavaScript which calls a function only if it exists, with Jest

For code like this:

export const addMediaQueryEventListener = (media, onChange) => {
  if (root.matchMedia) {
    const mediaQueryList = root.matchMedia(media);
    ...

How can you test both code 'branches' with Jest, ie when root.matchMedia is falsy as well as when it exists?

I can mock matchMedia to be a function and assert that it's called OK. But to test the other way around in order to get 100% test coverage, I'd need to mock matchMedia to be falsy, but also assert that it hasn't been called as a function.

Is there a way to mock the property matchMedia to be falsy whilst also spying on matchMedia as a function? Or would this function need to be rewritten to make it testable?

I followed the advice from @Taplar in the comments (thanks again!) and solved it like this:

describe('when matchMedia is unsupported', () => {
    beforeEach(() => {
      root.matchMedia = undefined;
    });

    test('it does not error', () => {
      addMediaQueryEventListener(media, onChange);
    });
  });
});

I was getting caught up thinking what assertions to make, but simply calling the function is enough, because if it tried calling undefined as a function then it would error and fail the test. This brought the test coverage to 100% as desired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM