Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing javascript code style

I'm getting started with javascript unit testing (with Jasmine).

I have experience in unit testing C# code. But given that javascript is a dynamic language, I find it very useful to exploit that, and writing tests using the expressive power of javascript, for instance:

describe('known plugins should be exported', function(){
    var plugins = ['bundle','less','sass','coffee','jsn','minifyCSS','minifyJS','forward','fingerprint'];

    plugins.forEach(function(plugin){
        it('should export plugin named ' + plugin, function(){
            expect(all[plugin]).toBeDefined();
        });
    });
});

As far as doing this kind of non-conventional test-writing, I haven't gone further than doing this kind of tests (array with a list of test cases that are very similar)

So I guess my question is

Is it fine to write tests like this, or should I constrain myself to a more "statically typed" test fixture?

like image 933
bevacqua Avatar asked Oct 21 '22 14:10

bevacqua


1 Answers

Great question!

Yes, it is perfectly fine to write unit tests like this. It's even encouraged.

JavaScript being a dynamic language lets you mock objects really easily. DI and IoC are really easy to do. In general, testing with Jasmine (or Mocha which I personally prefer) is a pleasant and fun experience.

It's worth mentioning that since you're in a dynamic language you need to have tests you did not in statically typed languages. Tests commonly enforce members and methods existing, and types.

Having no interfaces to define your contract, often, your tests define your code's contract so it's really not uncommon to see tests do this sort of verification (like in your code) where you wouldn't in C#.

like image 51
Benjamin Gruenbaum Avatar answered Oct 27 '22 11:10

Benjamin Gruenbaum