簡體   English   中英

如何使用 Proxyquire 模擬 TypeScript 中的配置依賴項?

[英]How to mock a configuration dependency in TypeScript with Proxyquire?

我有一個 config.ts,它返回一個 object:

// Config is an interface that I use to know which values are expected
export default function getConfig(): Config {
     return {amount: 50}
}

我有一個依賴於 config.ts 的 class (../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() function 分配給./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 |                   
---------------|---------|----------|---------|---------|-------------------

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM