-1

I'm new to testing with sinon, and I'm a little bit confused here on how I could test all three types of the return values (Moto, Sedan, and Vehicle) with stub or maybe less preferrably spy. Could anybody help me on this ?

transportType.js

export function transportType() {
  if (isMoto()) {
    return 'Moto';
  } else if (isSedan()) {
    return 'Sedan';
  } else {
    return 'Vehicle';
  }
}

function isMoto() {
  return window.matchMedia('only screen and (max-device-width: 700px)').matches;
}

function isSedan() {
  return window.matchMedia(
      'only screen and (min-device-width: 800px) and (max-device-width: 1000px)'
    ).matches;
}

carType_test.js

import {assert} from 'chai';
import sinon from 'sinon';
import * as transportTypes from './transportType';

describe('transportType', () => {
 it('returns "Moto" if width matches', () => {
  sinon.stub(transportTypes, 'transportType')
 })
})
ssss
  • 303
  • 1
  • 4
  • 7
  • It doesn't make sense to stub `sinon.stub(transportTypes, 'transportType')` because it's the function you're testing. – Estus Flask Sep 17 '18 at 23:05

1 Answers1

1

It's impossible to test functions that weren't exported. They should be exported in order to be tested. As explained in this answer, it's also impossible to spy or mock ES module exports that are used within same module.

In this case tests should be functional, i.e. these are not functions but their effects that need to be mocked. This is possible since they use window.matchMedia that can be mocked:

let matchMediaOriginal;

beforeEach(() => {
  matchMediaOriginal = window.matchMedia;
  window.matchMedia = sinon.stub();
}

afterEach(() => {
  window.matchMedia = matchMediaOriginal;
}

it('returns "Moto" if width matches', () => {
  window.matchMedia.returns({ matches: true });
  expect(window.matchMedia).to.have.been.called.always.with('only screen and (max-device-width: 700px)');
  expect(transportType()).to.equal('Moto');
})

Packages like match-media-mock can also be used.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565