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

module.exports = new Tester();

When testing this singleton in Node.js using Jest

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

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

When running the test, I get an error saying "encountered a declaration exception. TypeError: Tester.loggit is not a function"

I tried using jest.requireActual to resolve it, but it's not fixing the error.

I don't want to export the class itself as it will be a singleton in my app.

Any input will be helpful.

1
  • 2
    Static method in a singleton? Why?.. Commented Mar 19, 2019 at 21:18

1 Answer 1

3

You want to export the class itself, not an instance of the class:

module.exports = Tester;

And if just have static methods, you could just export an object:

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

If you really want to have both a singleton and static properties (what purpose should that serve?!), then you can get the class from an instance using the constructor property:

 (new Tester).constructor.loggit("test") 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.