javascriptnode.jsunit-testingavamjs

AVA unit tests fails passed Javascript test specs


I am currently working with ES6 modules with .mjs extensions and creating test cases for some functions.

I have chosen AVA due to its support of this extension type but the test executions are not running as expected.

I assume the script is not being transformed properly or I am missing a configuration in my package.json

I appreciate any help at all from anyone with experience with using AVA with --experimental-modules

package.json

{
    "scripts": {
        "test": "ava --init"
    },
    "ava": {
        "require": [
      "esm"
    ],
        "babel": false,
        "extensions": [
      "mjs"
    ]
    }
}

test.spec.mjs

import rotate from './index.mjs'
import test from 'ava';

test('rotate img', t => {
    var m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
    rotate(m);

    t.is(m, [[7, 4, 1], [8, 5, 2], [9, 6, 3]]);
});

index.js

 var rotate =function(matrix) {
    let cols = 0,
     original = JSON.parse(JSON.stringify(matrix));

    for (let i=0; i < matrix.length; i++){
        for (let j = matrix.length; j > 0; j--){
            matrix[i][cols]=original[j-1][i]; 

            cols+=1;
            if(cols == matrix.length){
                cols= 0;
            }
        }
    }
}
export default rotate;

On running npm test as defined in package script

ERROR:

 1 test failed

  rotate

   12: rotate(m);
   13:     t.is(m, [[7,4,1],[8,5,2],[9,6,3]
   14: ]);

  Values are deeply equal to each other, but they are not the same:

  [[7,4,1,],[8,5,2,],[9,6,3,],] <<fails

npm ERR! Test failed.  See above for more details.

Solution

  • AVA does not support .mjs out of the box, but it looks like you figured out the configuration.

    For the test script, just use ava, without the --init.

    All that said, the test is failing because you're using the wrong assertion. t.is(actual, expected) uses Object.is(actual, expected) (which is pretty much actual === expected). And you can't compare arrays like that.

    Use t.deepEqual() instead.