// tester.js
class Tester {
  static loggit(text) {
    return text;
  }
}

module.exports = new Tester();


使用Jest在Node.js中测试此单例时

// tester.spec.js
const Tester = require('./tester.js');

describe('Tester testing', () => {
  it('logs it', () => {
    expect(Tester.loggit('test')).toEqual('test');
  });
});


运行测试时,出现错误消息“遇到声明异常。TypeError:Tester.loggit不是函数”

我尝试使用jest.requireActual来解决它,但是它不能解决错误。

我不想导出类本身,因为它将在我的应用程序中成为单例。

任何输入都会有所帮助。

最佳答案

您要导出类本身,而不是类的实例:

module.exports = Tester;


如果只有static方法,则可以导出一个对象:

 module.exports = {
  loggit(it) { return it; },
 };


如果您确实想同时拥有单例和静态属性(这有什么用处?!),则可以使用构造函数属性从实例获取类:

 (new Tester).constructor.loggit("test")

10-08 08:13
查看更多