上面提到的方法(使用afactory
来收集函数)效果很好;但是,eslint 不喜欢使用尚未声明的变量/函数。因此,我建议稍作修改:
// my-functions.js
export const factory = {};
export const funcA = () => {
return facory.funcB();
};
factory.funcA = funcA;
export const funcB = () => true;
factory.funcB = funcB;
// my-functions-test.js
import {factory, funcA, funcB} from './path/to/my-functions';
describe('MyFunctions | funcA', () => {
test('returns result from funcB call', () => {
const funcBStub = sinon.stub(factory, 'funcB').returns(false);
// Test that the function does not throw errors
let result;
expect(() => (result = funcA())).not.toThrow();
// Test that the return value is that of the mock rather than the original function
expect(result).toEqual(false);
// Test that the stub was called
expect(funcBStub.called).toEqual(true);
});
});
// Don't forget to test funcB independently ;)
重要的区别是将文件中的函数添加到factory
定义时,以避免破坏 eslint 规则。这可能导致问题的唯一情况是,如果您尝试在所有函数被定义之前在同一文件中调用其中一个函数。例子:
// my-functions-1.js
export const factory = {};
export const funcA = () => {
factory.funcB();
};
factory.funcA = funcA;
// Since the code execution runs from top to bottom, calling funcA here means that funcB has not yet been added to factory
funcA(); // Throws an error since factory.funcB() is not a function (yet)
export const funcB = () => true;
factory.funcB = funcB;
我更喜欢这种使用“收集器”来调用同一文件中的函数的技术,因为为您编写的每个函数创建单独的文件并不总是一个好主意。通常,我发现我会创建许多相关的实用程序函数,以使我的代码更具可读性、可重用性和可组合性;将每个函数放在一个单独的文件中会使代码更难理解,因为如果不在不同的文件之间跳转,读者就无法看到这些函数的定义。