使用sinon存根测试辅助函数

问题描述 投票:-1回答:1

我是初次尝试使用sinon,我在这里有点困惑我如何测试所有三种类型的返回值(MotoSedanVehicle)与存根或者可能不太优选的间谍。有人可以帮我吗?

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')
 })
})
reactjs sinon
1个回答
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这样的包。

© www.soinside.com 2019 - 2024. All rights reserved.