我有一个config.ts,它返回一个对象:
// Config is an interface that I use to know which values are expected
export default function getConfig(): Config {
return {amount: 50}
}
我有一个类(../src/models/item.model(,它依赖于config.ts:
import getConfig from '../config/config';
class Item{
_id: number;
amount: number;
constructor(_id: number) {
this._id = _id;
this.amount = getConfig().amount;
}
}
export default Item
我想写一些不同数值的测试。默认值是50(在config.ts中设置(,但在我的item.test.ts中,我希望使用值100。我正试图通过使用Proxyquire:来实现这一点
it('should use voxelsize of custom config', (done) => {
const itemModel = proxyquire('../src/models/item.model', {
'../config/config': function getConfig() {
return {amount: 100};
}
}).default;
const testItem = new itemModel(1)
expect(testItem.amount).to.equal(100);
done()
})
testItem.amount实际上是50(所以它仍然使用原始配置文件(。这应该是100。
我怎样才能通过考试?
您使用的是es6export default function getConfig() {}
,因此应该将模拟的getconfig()
函数分配给./config
commonJS模块的default
属性。
例如
config.ts
:
export default function getConfig() {
return { amount: 50 };
}
item.model.ts
:
import getConfig from './config';
class Item {
_id: number;
amount: number;
constructor(_id: number) {
this._id = _id;
this.amount = getConfig().amount;
}
}
export default Item;
item.model.test.ts
:
import { expect } from 'chai';
import proxyquire from 'proxyquire';
describe('66691249', () => {
it('should use voxelsize of custom config', () => {
const itemModel = proxyquire('./item.model', {
'./config': {
default: function getConfig() {
return { amount: 100 };
},
},
}).default;
const testItem = new itemModel(1);
expect(testItem.amount).to.equal(100);
});
});
测试结果:
66691249
✓ should use voxelsize of custom config (1742ms)
1 passing (2s)
---------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files | 83.33 | 100 | 50 | 83.33 |
config.ts | 50 | 100 | 0 | 50 | 2
item.model.ts | 100 | 100 | 100 | 100 |
---------------|---------|----------|---------|---------|-------------------