2017-02-25 42 views
-2

我使用這個逃生功能的正則表達式:JS:如何測試一個逃生功能的正則表達式

escapeRegExp = (str) => { 
    return String(str).replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1') 
} 

現在我想編寫此功能的簡單測試。所以我想出了這個:

it('escapes a regular expression string',() => { 
    const input = '/path/to/resource.html?search=query', 
      result = '\\/path\\/to\\/resource\\.html\\?search\\=query' 

    expect(escapeRegExp(input)).to.equal(result) 
}) 

但是這不會涵蓋所有轉義的選項,它包含在函數中。

我該如何獲得更好的測試?

回答

0

這個方法在不同的庫中有一些公平的實現。

這裏就是這樣的一個庫:https://github.com/ljharb/regexp.escape

如果你需要測試你自己,然後測試所有場景將採取的測試相當數量 - 爲函數存在,人們必須已經寫測試它 - 對例如原型具有如下的測試:

assert.equal('word', RegExp.escape('word')); 
assert.equal('\\/slashes\\/', RegExp.escape('/slashes/')); 
assert.equal('\\\\backslashes\\\\', RegExp.escape('\\backslashes\\')); 
assert.equal('\\\\border of word', RegExp.escape('\\border of word')); 

assert.equal('\\(\\?\\:non-capturing\\)', RegExp.escape('(?:non-capturing)')); 
assert.equal('non-capturing', new RegExp(RegExp.escape('(?:') + '([^)]+)').exec('(?:non-capturing)')[1]); 

assert.equal('\\(\\?\\=positive-lookahead\\)', RegExp.escape('(?=positive-lookahead)')); 
assert.equal('positive-lookahead', new RegExp(RegExp.escape('(?=') + '([^)]+)').exec('(?=positive-lookahead)')[1]); 

assert.equal('\\(\\?<\\=positive-lookbehind\\)', RegExp.escape('(?<=positive-lookbehind)')); 
assert.equal('positive-lookbehind', new RegExp(RegExp.escape('(?<=') + '([^)]+)').exec('(?<=positive-lookbehind)')[1]); 

assert.equal('\\(\\?\\!negative-lookahead\\)', RegExp.escape('(?!negative-lookahead)')); 
assert.equal('negative-lookahead', new RegExp(RegExp.escape('(?!') + '([^)]+)').exec('(?!negative-lookahead)')[1]); 

assert.equal('\\(\\?<\\!negative-lookbehind\\)', RegExp.escape('(?<!negative-lookbehind)')); 
assert.equal('negative-lookbehind', new RegExp(RegExp.escape('(?<!') + '([^)]+)').exec('(?<!negative-lookbehind)')[1]); 

assert.equal('\\[\\\\w\\]\\+', RegExp.escape('[\\w]+')); 
assert.equal('character class', new RegExp(RegExp.escape('[') + '([^\\]]+)').exec('[character class]')[1]); 

assert.equal('<div>', new RegExp(RegExp.escape('<div>')).exec('<td><div></td>')[0]); 

assert.equal('false', RegExp.escape(false)); 
assert.equal('undefined', RegExp.escape()); 
assert.equal('null', RegExp.escape(null)); 
assert.equal('42', RegExp.escape(42)); 

assert.equal('\\\\n\\\\r\\\\t', RegExp.escape('\\n\\r\\t')); 
assert.equal('\n\r\t', RegExp.escape('\n\r\t')); 
assert.equal('\\{5,2\\}', RegExp.escape('{5,2}')); 

assert.equal(
    '\\/\\(\\[\\.\\*\\+\\?\\^\\=\\!\\:\\$\\{\\}\\(\\)\\|\\[\\\\\\]\\\\\\\/\\\\\\\\\\]\\)\\/g', 
    RegExp.escape('/([.*+?^=!:${}()|[\\]\\/\\\\])/g') 
);h 

https://github.com/sstephenson/prototype/blob/master/test/unit/tests/regexp.test.js

有是一個ES7提案來標準化這種方法:https://github.com/benjamingr/RegExp.escape

+1

RegExp.escape只是ES7的建議,不是嗎? – user3142695

+0

@ user3142695是的好點我會糾正我的答案,但在測試方面,車輪已經建成。 – Theo