Reactjs 使用sinon存根测试助手函数
我刚开始使用sinon进行测试,我在这里有点困惑,我怎么能用存根测试所有三种类型的返回值(Reactjs 使用sinon存根测试助手函数,reactjs,sinon,Reactjs,Sinon,我刚开始使用sinon进行测试,我在这里有点困惑,我怎么能用存根测试所有三种类型的返回值(Moto,Sedan,和Vehicle),或者更不喜欢spy。有人能帮我吗 transportType.js export function transportType() { if (isMoto()) { return 'Moto'; } else if (isSedan()) { return 'Sedan'; } else { return 'Vehicle';
Moto
,Sedan
,和Vehicle
),或者更不喜欢spy。有人能帮我吗
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;
}
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')
})
})
carType_test.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;
}
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')
})
})
无法测试未导出的函数。应将其导出以便进行测试。如中所述,也不可能监视或模拟同一模块中使用的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');
})
也可以使用类似的包。stub
sinon.stub(transportTypes,'transportType')没有意义,因为它是您正在测试的函数。