不确定这是否可行,我有一个在100+文件中使用的助手方法:
// helpers.ts
// exports a json object using export default
import STATIC_DATA from '@data/static-data';
export function getData(key: StaticDataKey) {
return STATIC_DATA[key].include ? 'foo' : 'bar';
}这个助手方法做了更多的工作,但是我简化了我的示例
在测试环境中
import assert from 'assert';
it('should return foo when include is true', () => {
const isFoo = getData('someKey');
assert.equal(isFoo, 'foo');
});
it('should return bar when include is false', () => {
const isBar = getData('someOtherKey');
assert.equal(isBar, 'bar');
});我想要做的是,在每个测试中模拟在helpers.ts文件中导入的“helpers.ts”是什么,这样我就可以强制数据达到我想要的结果,所以测试始终是真实的(例如,我知道它不起作用)。
it('should return bar when include is false', () => {
proxyquire('@data/static-data', {
someOtherKey:{
include: false
}
});
const isBar = getData('someOtherKey');
assert.equal(isBar, 'bar');
});我试过使用nock,sinon,proxyrequire,但没有成功
发布于 2022-05-20 03:16:56
只需在每个测试用例中将测试数据设置为STATIC_DATA,并在每个测试用例结束时清除它。
static-data.ts
export default {};helper.ts
import STATIC_DATA from './static-data';
export function getData(key) {
return STATIC_DATA[key].include ? 'foo' : 'bar';
}helper.test.ts
import { getData } from './helper';
import sinon from 'sinon';
import STATIC_DATA from './static-data';
describe('72312542', () => {
it('should return bar when include is false', () => {
STATIC_DATA['someOtherKey'] = { include: false };
const isBar = getData('someOtherKey');
sinon.assert.match(isBar, 'bar');
delete STATIC_DATA['someOtherKey'];
});
it('should return foo when include is true', () => {
STATIC_DATA['someKey'] = { include: true };
const isFoo = getData('someKey');
sinon.assert.match(isFoo, 'foo');
delete STATIC_DATA['someKey'];
});
});测试结果:
72312542
✓ should return bar when include is false
✓ should return foo when include is true
2 passing (4ms)
----------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
helper.ts | 100 | 100 | 100 | 100 |
static-data.ts | 100 | 100 | 100 | 100 |
----------------|---------|----------|---------|---------|-------------------https://stackoverflow.com/questions/72312542
复制相似问题