Proxyquire 没有存根我需要 class

Proxyquire not stubbing my required class

我有一个 class AProvider 需要 './b.provider'.

const BProvider = require('./b.provider');

class AProvider {
  static get defaultPath() {
    return `defaults/a/${BProvider.getThing()}`;
  }
}

module.exports = AProvider;

b.provider.jsa.provider.js 相邻并且看起来像

global.stuff.whatever = require('../models').get('Whatever'); // I didn't write this!

class BProvider {
  static getThing() {
    return 'some-computed-thing';
  }
}
module.exports = BProvider;

在我的测试中,我使用 proxyquire 来模拟 ./b.provider,如下所示:

import { expect } from 'chai';
import proxyquire from 'proxyquire';

describe('A Provider', () => {
  const Provider = proxyquire('../src/a.provider', {
    './b.provider': {
      getThing: () => 'b-thing'
    },
  });

  describe('defaultPath', () => {
    it('has the expected value', () => {
      expect(Provider.defaultPath).to.equal('defaults/a/b-thing')
    });
  });
});

然而,当我 运行 时,测试 BProvider 仍然需要实际的 './b.provider' 而不是存根,并且 BProvider 对 global.stuff.whatever 的引用会引发错误。

为什么这不起作用?

为什么会这样,答案如下

proxyquire 在将其存根之前仍然需要底层代码。它这样做是为了启用调用。

解决方法就是明确禁止调用。

测试变为:

import { expect } from 'chai';
import proxyquire from 'proxyquire';

describe('A Provider', () => {
  const Provider = proxyquire('../src/a.provider', {
    './b.provider': {
      getThing: () => 'b-thing',
      '@noCallThru': true
    },
  });

  describe('defaultPath', () => {
    it('has the expected value', () => {
      expect(Provider.defaultPath).to.equal('defaults/a/b-thing')
    });
  });
});

运行 这个测试非常有效。