0

我正在使用 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文件所在的“根”目录中查找的,而不是src预期的目录。

4

1 回答 1

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(并且可能是转译器)。

于 2017-08-01T14:18:39.867 回答