不確定這是否可行,我有一個用于 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 檔案中匯入的“STATIC_DATA”是什么,所以我可以強制資料是我想要的,因此測驗始終保持真實,例如(其中我知道不起作用)
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 但沒有成功:(
uj5u.com熱心網友回復:
只需在每個測驗用例中設定測驗資料并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://www.uj5u.com/qiye/481721.html
上一篇:賽普拉斯未在ciSyntaxError中運行:使用cypress-io/github-action@v2typescript的意外令牌“匯出”
下一篇:Django測驗單元登錄用戶
