代码:
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
发布于 2020-05-03 07:04:18
在从字符串文字构建的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" ); }
https://stackoverflow.com/questions/61566747
复制相似问题