使用sinon存根测试助手功能

时间:2018-09-17 21:50:12

标签: reactjs sinon

我刚开始使用sinon进行测试,在这里我对如何测试所有三种类型的返回值(SedanVehicle和{{1 }})带有存根或不太受欢迎的间谍。有人可以帮我吗?

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')
 })
})

1 个答案:

答案 0 :(得分:0)

不可能测试未导出的功能。它们应该被导出以便进行测试。如this answer中所述,也不可能监视或模拟在同一模块中使用的ES模块导出。

在这种情况下,测试应该是功能性的,即,这些不是功能性的,而是需要模拟的效果。这是可能的,因为他们使用了可以模拟的window.matchMedia

let matchMediaOriginal;

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

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

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');
})

也可以使用match-media-mock之类的软件包。