5

My experience is with statically typed languages, and I must admit that I feel lost when trying to achieve the same with dynamic languages. One of the things that I would like to avoid, is apply concepts that don't make sense in this context. Please, assume that this class belongs to my project and that we want to test it with Jasmine:

class MyEs6Class {
    constructor(
        collaborator1 = new MyCollaborator(),
        factory = new MyFactory()) {

        this.collaborator1 = collaborator1;
        this.factory = factory;
    }

    method() {
        // Code
    }
}

I'm providing default instances of the objects in the constructor because that allows me to mock them when testing. I'm trying to use inversion of control in the same way that I would use with, let's say C#, but using the dynamic features of the language to avoid a Dependency Injection container. These two dependencies are required by the class, so from the structural point of view, I think is very clear that they must be provided using the constructor.

Also, I'm using the concept of a factory only because while the class is 'alive' can require new objects from the factory several times.

From the point of view of ES6 classes, I know that there is no difference between private and public (https://stackoverflow.com/a/27853642/185027), so I could have the logic handled by the factory in a private method, but depend on him testing seems just wrong. On the other side having something called factory just because I need to fake the objects that returns seems weird, and maybe is screaming my lack of knowledge.

  • What is the proper way to mock collaborators in this context?.
  • Is it silly to have the concept of a factory only because I need to mock the object that returns?.
  • What would be a maintainable and elegant way of isolating the subject under test in Javascript/ES6?. Any interesting public codebase that I can study?.
Community
  • 1
  • 1
Jacob
  • 1,886
  • 2
  • 25
  • 40
  • Are you trying to use default arguments?, there is no such thing for Javascript. this.methodName = function() { ... } is public, whereas var methodName = function() { ... } is private. To test ES6 use Node and classes are just a syntactical sugar that I my opinion are more confusing if you do not alreasy have an idea about how OO works in JS – Noctisdark Mar 11 '16 at 19:41
  • http://sinonjs.org/ ? – Evan Davis Mar 11 '16 at 19:49
  • Thanks for the comments!. Noctisdark, not sure I got you completely, but the default arguments that I show are working with ES6 (not sure that worked like that before). Mathletics, more than a framework, I'm trying to get an structural idea about testing in ES6 and JS. – Jacob Mar 11 '16 at 20:10
  • 2
    @Noctisdark You can provide default values for parameters in ES6. – a better oliver Mar 11 '16 at 20:20
  • 1
    Great !, Today, I get rid of || ! – Noctisdark Mar 11 '16 at 20:40

0 Answers0