我有一个构造数组的函数,比如[{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();
}
};
};发布于 2016-03-22 11:09:57
默认情况下,Wallaby.js在幕后使用PhantomJ,它使用与Safari相同的JavaScript引擎。如果您在Safari开发工具中运行此代码片段

您会注意到,它也不会按预期对数组进行排序。Chrome Dev Tools将向您显示不同的结果:

因此,如果你想让你的sort实现在所有的平台上都能工作,你需要将它改为compliant with the spec并返回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;
});那么它将在任何地方都能正常工作。如果您更喜欢更短(但可读性稍差)的方法,您可以使用以下方法:
export default function(array) {
return array.sort((x, y) => +(x.index > y.index) || +(x.index === y.index) - 1);
}如果出于某种原因,你只想支持你的原始代码工作的平台,而不想改变它,那么我建议将默认的PhantomJs运行器切换到wallaby也支持的Electron runner。它使用V8,您的原始代码可以很好地使用它。
https://stackoverflow.com/questions/36023384
复制相似问题