Javascript array.sort在wallby.js中的行为异常
我有一个函数,它构造了一个数组,比如,Javascript array.sort在wallby.js中的行为异常,javascript,wallaby.js,Javascript,Wallaby.js,我有一个函数,它构造了一个数组,比如,[{index:1},{index:4},{index:7}]。数组按对象的索引值排序。我已经将函数的范围缩小到只对数组进行排序,wallaby表示数组的顺序不正确,但是mocha继续表示通过了测试 规格为: import expect from 'expect'; import sort from './sort'; describe("Given an array", ()=> { let array; beforeEach(()
[{index:1},{index:4},{index:7}]
。数组按对象的索引值排序。我已经将函数的范围缩小到只对数组进行排序,wallaby表示数组的顺序不正确,但是mocha继续表示通过了测试
规格为:
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});
}
我的wallaby配置如下所示:
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();
}
};
};
默认情况下,Wallaby.js在幕后使用PhantomJs,它使用与Safari相同的JavaScript引擎。如果您在Safari开发工具中运行此代码段: 您会注意到,它也没有按预期对数组进行排序Chrome开发工具将显示不同的结果: 因此,如果您希望您的
排序
实现在所有平台上运行,则需要将其更改为并返回1
、-1
或0
,而不仅仅是true
或false
因此,如果以这种方式重写排序函数:
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;
});
如果出于某种原因,您只想支持原始代码工作的平台,而不想更改它,那么我建议将默认的PhantomJs运行程序切换到wallaby也支持的平台。它使用V8,您的原始代码可以很好地使用它
export default function(array) {
return array.sort((x, y) => +(x.index > y.index) || +(x.index === y.index) - 1);
}