【问题标题】:Require not behaving as expected要求行为不符合预期
【发布时间】:2018-01-08 08:20:15
【问题描述】:

我正在使用 proxyquire 库,它在导入时模拟包。

我正在创建自己的 proxyquire 函数,它会存根我经常使用并希望定期存根的各种包(meteor 包,它具有特殊的导入语法):

// myProxyquire.js
import proxyquire from 'proxyquire';

const importsToStub = {
  'meteor/meteor': { Meteor: { defer: () => {} } },
};

const myProxyquire = filePath => proxyquire(filePath, importsToStub);

export default myProxyquire;

现在我想编写一个使用以下软件包之一的文件测试:

// src/foo.js
import { Meteor } from 'meteor/meteor'; // This import should be stubbed

export const foo = () => {
  Meteor.defer(() => console.log('hi')); // This call should be stubbed
  return 'bar';
};

最后我像这样测试它:

// src/foo.test.js
import myProxyquire from '../myProxyquire';

// This should be looking in the `src` folder
const { foo } = myProxyquire('./foo'); // error: ENOENT: no such file

describe('foo', () => {
  it("should return 'bar'", () => {
    expect(foo()).to.equal('bar');
  });
});

请注意,我最后的 2 个文件嵌套在子文件夹 src 中。因此,当我尝试运行此测试时,我收到一条错误消息,提示找不到模块 ./foo,因为它正在“根”目录中查找,myProxyquire.js 文件所在的位置,而不是 @ 987654327@ 目录符合预期。

【问题讨论】:

  • 如果你用普通的require 替换了对proxyquire 的调用,你也会遇到同样的问题,因为require 就是这样工作的:它加载相对于文件 的文件包含对require 的调用,在您的情况下为myProxyquire.js
  • 我也是这么想的,有办法解决吗?

标签: javascript testing meteor proxyquire


【解决方案1】:

您可以通过使用像 caller-path 这样的模块来确定从哪个文件调用 myProxyquire 并解析相对于该文件的传递路径,从而解决该(预期的)行为:

'use strict'; // this line is important and should not be removed

const callerPath           = require('caller-path');
const { dirname, resolve } = require('path');

module.exports.default = path => require(resolve(dirname(callerPath()), path));

但是,我不知道这适用于 import(可能还有转译器)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多