【问题标题】:Proxyquire not stubbing my required classProxyquire 没有存根我需要的类
【发布时间】:2017-07-21 20:48:11
【问题描述】:

我有一个需要'./b.provider' 的课程AProvider

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 的引用会引发错误。

为什么这不起作用?

【问题讨论】:

  • 您是否尝试过在before 语句中声明proxyquire 指令?另外,不确定这是否会有所帮助,但本文似乎认为有必要同时使用 sinon:thoughtdelimited.org/thoughts/post.cfm/…
  • 有趣的链接。尽管 proxyquire,我没有意识到 Require 仍然发生。现在在出租车上,但我回家后会测试解决方案。谢谢。
  • 好的,我已经解决了问题并找到了一个简单的解决方案,我将在下面发布。感谢@francisco.preller 为我指明了正确的方向。
  • 我尝试了@Dave Sag 的帖子,但它没有用......但是,我发现如果我需要像这样const proxyquire = require("proxyquire").noCallThru(); 的代理查询,一切都很好!
  • @francisco.preller 您好想阅读那篇文章,但链接已失效。请您再指点一下好吗?

标签: javascript unit-testing es6-class proxyquire


【解决方案1】:

为什么会这样的答案如下

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')
    });
  });
});

运行此测试完美无缺。

【讨论】:

    猜你喜欢
    • 2018-05-05
    • 2015-07-08
    • 2017-12-23
    • 2017-01-27
    • 2021-09-23
    • 2018-08-12
    • 2019-08-18
    • 1970-01-01
    相关资源
    最近更新 更多