如何使用 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() 函数分配给 default commonJS 模块的 ./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 |                   
---------------|---------|----------|---------|---------|-------------------

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...