We were writing a spec yesterday where we had a method that was returning an array of numbers in no particular order, and we wanted to verify its output. It went something like:
expect(model.foo().sort()).toEqual([1, 2, 3, 10, 25]);
The error message from Jasmine was something like “expected [1, 10, 2, 25, 3] to equal [1, 2, 3, 10, 25]”.
I couldn’t believe it. I wanted to sort an array of numbers, and JavaScript decided it would do me a favor and cast them all to strings first.
The workaround is simple: Mozilla recommends just passing a comparison function to sort:
expect(model.foo().sort(function(a, b) {
return a-b;
})).toEqual([1, 2, 3, 10, 25]);
When you’re working in JavaScript everyday, you learn to expect the unexpected to some extent, but even this one threw me off.
About the Author