how to test this regex in jest

if (typeof fields["emailid"] !== "undefined") {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    if (!pattern.test(fields["emailid"])) {
      formIsValid = false;
      errors["emailid"] = "*Please enter valid email-ID.";
    }
}

I know the question is quite old by now and I don't even know if the following solution already existed at the time of asking, but I think the Jest-most way would be:

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

Potentially also produces a more descriptive error message in case of failure.

For further reference: https://jestjs.io/docs/en/expect#tomatchregexporstring


You just need to import the exported const to your test file. Try this:

regexp.js

export const matchUriRE = /^([^:]*):([^:]*):(.*)$/;

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);
  });
});