Javascript 要求行为不符合预期
我正在使用proxyquire库,它在导入时模拟包 我正在创建我自己的proxyquire函数,该函数定期存根我经常使用并希望定期存根的各种包(meteor包,具有特殊的导入语法): 现在,我想编写一个文件的测试,该文件使用以下软件包之一:Javascript 要求行为不符合预期,javascript,testing,meteor,proxyquire,Javascript,Testing,Meteor,Proxyquire,我正在使用proxyquire库,它在导入时模拟包 我正在创建我自己的proxyquire函数,该函数定期存根我经常使用并希望定期存根的各种包(meteor包,具有特殊的导入语法): 现在,我想编写一个文件的测试,该文件使用以下软件包之一: // src/foo.js import { Meteor } from 'meteor/meteor'; // This import should be stubbed export const foo = () => { Meteor.de
// 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');
});
});
请注意,我的最后两个文件嵌套在子文件夹
src
中。因此,当我尝试运行此测试时,我收到一个错误消息,表示无法找到模块/foo
,因为它正在“root”目录中查找,而myProxyquire.js
文件所在的是src
目录,而不是预期的src
目录使用模块确定调用哪个文件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
(可能还有Transpiler)。如果您将对proxyquire
的调用替换为常规的require
,您也会遇到同样的问题,因为require
就是这样工作的:它相对于包含对require
的调用的文件加载文件,在你的例子中,哪个是myProxyquire.js
我也是这么想的,有办法解决这个问题吗?
'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));