Mocha Chai 正则表达式是相等的
Mocha Chai regex are equals
我正在尝试测试生成正则表达式的方法的行为。
使用 Mocha/Chai 测试套件我有以下代码:
describe('regexTest',function () {
it('should return a regexp', function () {
var regex = regexTest();
assert.equal(regex, /someregex/);
});
});
但是上面的代码好像不行。我在 chrome 控制台中尝试过:
/a/ == /a/
> false
目前我找到的唯一方法是比较两个正则表达式的 toString
(应该相等并且我可以比较):
describe('regexTest',function () {
it('should return a regexp', function () {
var regex = regexTest();
assert.equal(regex.toString(), '/someregex/');
});
});
您知道更好的方法吗?因为我觉得这不是很干净...
以下是我测试文字正则表达式是否有效的方法:
var assert = require('assert');
describe('RegExp Test', function() {
it('should return a valid RegExp', function() {
var getSomeRegex = function() {
return /someregex/;
};
var aRegex = getSomeRegex();
assert.equal(aRegex instanceof RegExp, true);
});
it('should return a invalid Regexp', function() {
var getInvalidRegex = function() {
return '/something';
};
var aInvalidRegex = getInvalidRegex();
assert.equal(aInvalidRegex instanceof RegExp, false);
});
});
有点晚了,但对于其他以我的方式 Google 偶然发现此问题的人来说,Chai 的正常比较函数也适用于 Regexp 对象...
const re = new RegExp( '^foo.*bar$', 'i' );
re.should.eql( /^foo.*bar$/i );
由于正则表达式是一个对象,你需要使用深度等于来比较 2 个正则表达式对象
expect(/a/).to.be.deep.equal(/a/, 'should match')
我正在尝试测试生成正则表达式的方法的行为。
使用 Mocha/Chai 测试套件我有以下代码:
describe('regexTest',function () {
it('should return a regexp', function () {
var regex = regexTest();
assert.equal(regex, /someregex/);
});
});
但是上面的代码好像不行。我在 chrome 控制台中尝试过:
/a/ == /a/
> false
目前我找到的唯一方法是比较两个正则表达式的 toString
(应该相等并且我可以比较):
describe('regexTest',function () {
it('should return a regexp', function () {
var regex = regexTest();
assert.equal(regex.toString(), '/someregex/');
});
});
您知道更好的方法吗?因为我觉得这不是很干净...
以下是我测试文字正则表达式是否有效的方法:
var assert = require('assert');
describe('RegExp Test', function() {
it('should return a valid RegExp', function() {
var getSomeRegex = function() {
return /someregex/;
};
var aRegex = getSomeRegex();
assert.equal(aRegex instanceof RegExp, true);
});
it('should return a invalid Regexp', function() {
var getInvalidRegex = function() {
return '/something';
};
var aInvalidRegex = getInvalidRegex();
assert.equal(aInvalidRegex instanceof RegExp, false);
});
});
有点晚了,但对于其他以我的方式 Google 偶然发现此问题的人来说,Chai 的正常比较函数也适用于 Regexp 对象...
const re = new RegExp( '^foo.*bar$', 'i' );
re.should.eql( /^foo.*bar$/i );
由于正则表达式是一个对象,你需要使用深度等于来比较 2 个正则表达式对象
expect(/a/).to.be.deep.equal(/a/, 'should match')