Browse Source

Typecheck arguments to t.regex() and t.notRegex()

master
Mark Wubben 8 years ago
committed by Sindre Sorhus
parent
commit
f06298179a
  1. 30
      lib/assert.js
  2. 40
      test/assert.js

30
lib/assert.js

@ -300,6 +300,21 @@ function wrapAssertions(callbacks) {
},
regex(string, regex, message) {
if (typeof string !== 'string') {
throw new AssertionError({
assertion: 'regex',
message: '`t.regex()` must be called with a string',
values: [formatAssertError.formatWithLabel('Called with:', string)]
});
}
if (!(regex instanceof RegExp)) {
throw new AssertionError({
assertion: 'regex',
message: '`t.regex()` must be called with a regular expression',
values: [formatAssertError.formatWithLabel('Called with:', regex)]
});
}
if (!regex.test(string)) {
throw new AssertionError({
assertion: 'regex',
@ -313,6 +328,21 @@ function wrapAssertions(callbacks) {
},
notRegex(string, regex, message) {
if (typeof string !== 'string') {
throw new AssertionError({
assertion: 'notRegex',
message: '`t.notRegex()` must be called with a string',
values: [formatAssertError.formatWithLabel('Called with:', string)]
});
}
if (!(regex instanceof RegExp)) {
throw new AssertionError({
assertion: 'notRegex',
message: '`t.notRegex()` must be called with a regular expression',
values: [formatAssertError.formatWithLabel('Called with:', regex)]
});
}
if (regex.test(string)) {
throw new AssertionError({
assertion: 'notRegex',

40
test/assert.js

@ -808,6 +808,26 @@ test('.regex()', t => {
t.end();
});
test('.regex() fails if passed a bad value', t => {
failsWith(t, () => {
assertions.regex(42, /foo/);
}, {
assertion: 'regex',
message: '`t.regex()` must be called with a string',
values: [{label: 'Called with:', formatted: /42/}]
});
failsWith(t, () => {
assertions.regex('42', {});
}, {
assertion: 'regex',
message: '`t.regex()` must be called with a regular expression',
values: [{label: 'Called with:', formatted: /Object/}]
});
t.end();
});
test('.notRegex()', t => {
passes(t, () => {
assertions.notRegex('abc', /def/);
@ -837,3 +857,23 @@ test('.notRegex()', t => {
t.end();
});
test('.notRegex() fails if passed a bad value', t => {
failsWith(t, () => {
assertions.notRegex(42, /foo/);
}, {
assertion: 'notRegex',
message: '`t.notRegex()` must be called with a string',
values: [{label: 'Called with:', formatted: /42/}]
});
failsWith(t, () => {
assertions.notRegex('42', {});
}, {
assertion: 'notRegex',
message: '`t.notRegex()` must be called with a regular expression',
values: [{label: 'Called with:', formatted: /Object/}]
});
t.end();
});

Loading…
Cancel
Save