代码:错误:正则表达式无效。
it.only('should display logs in color when using chalk', () => {
// Setup.
const uuid = uuidv4();
const messages = [
// prettier-ignore
[`${uuid}_chalk_info`, '\[37mINFO\[39m'],
[`${uuid}_chalk_debug`, '\[36mDEBUG\[39m'],
[`${uuid}_chalk_trace`, '\[32mTRACE\[39m']
];
testLog(messages[0][1]);
const log = languramaLog({ ...defaultTerminalConfiguration, level: 'trace', chalk });
const mock = jest.spyOn(process.stdout, 'write').mockImplementation(() => {});
// Test.
log.info(messages[0][0]);
log.debug(messages[1][0]);
log.trace(messages[2][0]);
// Assert.
expect(mock).toHaveBeenCalledTimes(3);
expect(mock).toHaveBeenCalledWith(jasmine.stringMatching(messages[0][1]));
expect(mock).toHaveBeenCalledWith(jasmine.stringMatching(messages[1][1]));
expect(mock).toHaveBeenCalledWith(jasmine.stringMatching(messages[2][1]));
});
错误。
SyntaxError: Invalid regular expression: /INFO/: Unterminated character class
at new RegExp (<anonymous>)
359 | // Assert.
360 | expect(mock).toHaveBeenCalledTimes(3);
> 361 | expect(mock).toHaveBeenCalledWith(jasmine.stringMatching(messages[0][1]));
| ^
362 | expect(mock).toHaveBeenCalledWith(jasmine.stringMatching(messages[1][1]));
363 | expect(mock).toHaveBeenCalledWith(jasmine.stringMatching(messages[2][1]));
364 | });
所以我使用的是 chalk
来为一些日志创建颜色,我想测试一下,以确保日志被打印到终端。然而,jasmine中的RegEx似乎在抱怨,有什么办法吗?
下面的代码可以正常工作。
const log = new RegExp(/\[37mINFO\[39m/);
const result = log.test('[90m2020-05-02 23:54:51 UTC+2[39m [37mINFO[39m 2df268af-af1f-42f0-b098-d52fb0123d95_chalk_info [90m/home/karl/dev/langurama/log/test/index.node.spec.js:358:17[39m');
console.log(result); // true
在由字符串字元建立的Regexen中,你必须将转义符加倍:一个例子是转义符是 \
字符串中的文字,以得出Regexp的转义字符。
所以你的模式会是这样的:
\\[37mINFO\\[39m
测试案例:
let re_s
, re_d
, re_s_nostring
, re_d_nostring
;
try { re_s = new RegExp ( '\[37mINFO\[39m', 'g' ); } catch (e) { console.log('re_s: constructor fails.\n' ); } // This always fails.
try { re_d = new RegExp ( '\\[37mINFO\\[39m', 'g' ); } catch (e) { console.log('re_d: constructor fails.\n' ); }
try { re_s_nostring = /\[37mINFO\[39m/g; } catch (e) { console.log('re_s_nostring: constructor fails.\n' ); }
// Syntactically wrong, won't compile into bytecode
// re_d_nostring = /\\[37mINFO\\[39m/g;
if (re_d) { console.log ( re_d.test("[37mINFO[39m") ? "re_d matches" : "re_d does not match" ); }
if (re_s_nostring) { console.log ( re_s_nostring.test("[37mINFO[39m") ? "re_s_nostring matches" : "re_s_nostring does not match" ); }