首页 > 解决方案 > 如何使用 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。

我怎样才能让测试通过?

标签: node.jstypescriptmockingproxyquire

解决方案


您正在使用 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 |                   
---------------|---------|----------|---------|---------|-------------------

推荐阅读