how to test this regex in jest

man*_*urt 10 javascript jestjs

I have this one-liner I need to test using jest

export const matchUriRE = /^([^:]*):([^:]*):(.*)$/;
Run Code Online (Sandbox Code Playgroud)

How to test it? Thanks in advance.

Ric*_*Dev 13

我知道这个问题现在已经很老了,我什至不知道在提问时是否已经存在以下解决方案,但我认为Jest -most 方法是:

it('matches URI', () => {
  const uriRegEx = /^([^:]*):([^:]*):(.*)$/;
  const uri = 'http://google.com:4443/'; 
  expect(uri).toMatch(uriRegEx);
});
Run Code Online (Sandbox Code Playgroud)

还可能在失败的情况下产生更具描述性的错误消息。

进一步参考:https : //jestjs.io/docs/en/expect#tomatchregexporstring


dys*_*unc 5

您只需要将导出的常量导入到您的测试文件中。尝试这个:

正则表达式

export const matchUriRE = /^([^:]*):([^:]*):(.*)$/;
Run Code Online (Sandbox Code Playgroud)

regexp.spec.js

import { matchUriRE } from './regexp';

describe('RegExp: URI', function(){
  it('should match the expected URI', function(){
    // include all the various cases to test the regexp against here
    // example:
    const uri = 'http://google.com:4443/'; 
    expect(matchUriRE.test(uri)).toBe(true);
  });
});
Run Code Online (Sandbox Code Playgroud)