2016-03-15 28 views
1

我有一個函數,構造一個數組,如[{index: 1}, {index: 4}, {index: 7}]。該數組按對象的索引值排序。我已經將函數的範圍縮小到只對數組進行排序,並且wallaby指示數組的順序不正確,但是mocha繼續指示通過測試。array.sort與wallaby.js的行爲奇怪

該規範是:

import expect from 'expect'; 
import sort from './sort'; 

describe("Given an array",()=> { 
    let array; 
    beforeEach(() => { 
     array = [ 
      { index: 7, owner: 1 }, 
      { index: 2, owner: 1 }, 
      { index: 3, owner: 1 }, 
      { index: 5, owner: 1 }, 
      { index: 1, owner: 1 } 
     ]; 
    }); 

    describe("When sorting the array of elements by id",() => { 

     let actual; 
     beforeEach(() => { 
      actual = sort(array); 
     }); 

     it('should order the array of objects by ascending id',()=> { 
      let expected = [ 
       { index: 1, owner: 1 }, 
       { index: 2, owner: 1 }, 
       { index: 3, owner: 1 }, 
       { index: 5, owner: 1 }, 
       { index: 7, owner: 1 } 
      ]; 

      expect(actual).toEqual(expected); 
     }); 
    }); 
}); 

sort.js的實現是:

export default function(array){ 
    return array.sort((x, y) => { return x.index > y.index}); 
} 

我的小袋鼠的配置是這樣的:

process.env.NODE_ENV = 'test'; 

var wallabyWebpack = require('wallaby-webpack'); 
var packageConfig = require('./package.json'); 

module.exports = function(wallaby) { 

    var specFilePattern = 'src/shared/**/*.spec.js'; 
    var srcFilePattern = 'src/shared/**/*.js*'; 

    var babelProcessor = wallaby.compilers.babel(packageConfig['babel']); 

    var webpackPostProcessor = wallabyWebpack({ 
    resolve: { 
      extensions: ['', '.js', '.jsx'] 
     } 
    }); 

    return { 
    testFramework: 'mocha', 
    debug: true, 
    files: [ 
     { pattern: 'node_modules/babel-polyfill/dist/polyfill.js', instrument: false }, 
     { pattern: srcFilePattern, load: false }, 
     { pattern: specFilePattern, ignore: true } 
    ], 
    tests: [ 
     { pattern: specFilePattern, load: false } 
    ], 
    compilers: { 
     '**/*.js*': babelProcessor 
    }, 
    postprocessor: webpackPostProcessor, 
    bootstrap: function(){ 
     window.__moduleBundler.loadTests(); 
    } 
    }; 
}; 

回答

1

Wallaby.js的背後是使用PhantomJs這是默認情況下的場景,它使用與Safari相同的JavaScript引擎。如果你在Safari開發工具運行這段代碼:

screen shot 2016-03-22 at 12 42 21 pm

,你會發現,它也不會陣列預期排序。 Chrome開發工具會告訴你一個不同的結果:

screen shot 2016-03-22 at 12 42 43 pm

所以,如果你想你的sort實現所有平臺上的工作,你需要改變它是compliant with the spec並返回1-10,而不僅僅是truefalse

所以,如果你重寫你的排序功能是這樣的:

export default function (array) { 
    return array.sort((x, y) => { 
    if (x.index > y.index) { 
     return 1; 
    } 
    if (x.index < y.index) { 
     return -1; 
    } 

    return 0; 
    }); 

那麼它會工作無處不在。如果你喜歡一個較短的(但少了幾分可讀)的方式,你可以使用這一個:

export default function(array) { 
    return array.sort((x, y) => +(x.index > y.index) || +(x.index === y.index) - 1); 
} 

如果由於某種原因,你只想支持平臺,在那裏你原來的代碼工作,並會不喜歡改變它,那麼我建議將默認的PhantomJs轉輪切換到wallaby也支持的Electron runner。它使用V8,您的原始代碼可以正常工作。