node.js - 如何使用 Proxyquire 在 TypeScript 中模拟配置依赖项?
问题描述
我有一个 config.ts 返回一个对象:
// Config is an interface that I use to know which values are expected
export default function getConfig(): Config {
return {amount: 50}
}
我有一个依赖于 config.ts 的类(../src/models/item.model):
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。
我怎样才能让测试通过?
解决方案
您正在使用 es6 export default function getConfig() {}
,因此您应该将模拟getconfig()
函数分配给commonJS 模块的default
属性。./config
例如
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 |
---------------|---------|----------|---------|---------|-------------------
推荐阅读
- android - × 组件 tns-core-modules 未安装。× 组件 tns-android 未安装。× 组件 tns-ios 未安装
- javascript - 如何在不重绘图表的情况下更新 highchart 中的向下钻取数据?
- python - 如何在 Python 中为 a 替换(环)?
- angular - 角度错误 TS2339:“订阅”类型上不存在属性“查找”
- android - Android 拆分 ABI armeabi-v8a 不工作。我不使用 ndk,但 arm 二进制文件仅适用于 armeabi-v8a
- regex - 仅从文本文件中提取日期并忽略大量数字
- java - Hibernate5 没有与 Spring5 进行交易?
- javascript - 替代 JQuery 切换
- python - 如何显式等待Python Selenium中文本框的属性值发生变化?
- jgrasp - 如何在 JGrasp 上更改小程序的大小?