How to test a Grunt task? Understanding and best practices

4.9k views Asked by At

I'm a bit stuck with understanding how to write complicated Gruntfile.js and use it with tests. Am I using Grunt in a right way? I would like to ask community for help and contribute in an other way.

I'm writing a new task for Grunt and want to roll it out for wide audience on Github and npm. I want to make automated testing for this task (and I want to learn how to do it properly!).

I want to test different options combinations (about 15 by now). So, I should multiple times:

  • run cleanup
  • run my task with next options set
  • run tests and pass options object to the test

Some non-working code to look at for better understanding:

Gruntfile:

grunt.initConfig({

    test_my_task: {
        testBasic: {
            options: {
                 //first set
            }
        },
        testIgnore: {
            options: {
                //another set
            }
        },

        //...
    }

    clean: {
        tests: ['tmp'] // mmm... clean test directory
    },

    // mmm... unit tests.
    nodeunit: {
        tests: ['test/*.js']  //tests code is in 'tests/' dir
    }
});

grunt.registerTask('test', ['test_my_task']);

I know how to check if tmp/ folder is in desired state when options object given.

The problem is putting things together.

I would ask just for template code as an answer, npo need to put working example.

PS: you can propose another testing tool, nodeunit is not a must.

PPS: crap, I could have written this in plain javascript by now! Maybe I'm doing wrong that I want to put Grunt into the unit tests? But I want to test how my task works in real environment with different options passed from Grunt...

1

There are 1 answers

1
Ben On

You might want to have a look at the grunt-lintspaces configuration. The tests look like this, and it seems like a good way to do it. grunt-lintspaces uses nodeunit but a lot of plugins these days seem to.

If you don't want to test actual grunt output and instead functionality, you could use grunt-mocha-test - https://github.com/pghalliday/grunt-mocha-test which I am using for the grunt-available-tasks tests. I prefer the describe style of testing personally, it reads very well; the advantage of using this is that you actually test what your plugin does without including a ton of config in your Gruntfile; i.e. test code should be in the tests.

Grunt is well tested already so it doesn't make sense to test that its configuration works. Just test the functionality of your own plugin.