我有以下代码按照标题对书籍进行排序:
function alphabetizeBookNodes(a, b) {
if (typeof a.title !== "undefined") {
var aTitle = _removeArticles(a.title.toLowerCase()),
bTitle = _removeArticles(b.title.toLowerCase());
} else {
var aTitle = _removeArticles(a.book.title.toLowerCase()),
bTitle = _removeArticles(b.book.title.toLowerCase());
}
if (aTitle > bTitle) return 1;
if (aTitle < bTitle) return -1;
return 0;
}
function _removeArticles(str) {
words = str.split(" ");
if(words.length <= 1) return str;
if( words[0] == 'a' || words[0] == 'the' || words[0] == 'an' ) {
return words.splice(1).join("");
}
return str;
}
module.exports = {alphabetizeBookNodes: alphabetizeBookNodes};
在浏览器中,行words = str.split(" ");
会抛出Uncaught ReferenceError: words is not defined
。它应该是let words = ...
。
我试图使用Karma / Jasmine测试触发该错误,如下所示:
describe("Utils", function() {
it('compares books by removing articles from the title', function() {
let alphabetizeBookNodes = require('../utils').alphabetizeBookNodes;
const bookA = {'title': 'The Grapes of Wrath'};
const bookB = {'title': 'Huckleberry Finn'};
let compare = function(a, b) {
return alphabetizeBookNodes(a, b);
}
let books = [bookB, bookA];
let sortedBooks = books.sort(compare);
expect(sortedBooks.length).toEqual(2);
expect(sortedBooks[0]).toEqual(bookA);
expect(sortedBooks[1]).toEqual(bookB);
});
});
为什么此测试不会触发ReferenceError
?如何重写此测试以便它能够捕获用户在浏览器中遇到的此错误?