Hello I was hoping someone could help me out with a problem I am having. In my tests I am checking certain fields to confirm that the value returned by the API matches the expected time date format. To do that I am using a regex, for example:
pm.expect(jsonData.value[0]['CreatedDt']).to.match(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/);
I would like to move the regex (ie, /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/) into a global variable that I can use instead so that if the format changes in the future I only have to change the regex in the variable instead of all my tests.
The problem is that once I swap out the regex for the global variable I am getting this error:
Value array item fields have expected type & formatting | TypeError: e.exec is not a function
I can’t seem to find a way to move the regex into a global variable & then use that variable in the match instead. Here is the code I am trying to write:
pm.test("Value array item fields have expected type & formatting", () => {
var regex = pm.globals.get("tds_regex");
pm.expect(jsonData.value[0]['CreatedDt']).to.match(regex);
});
If anyone has any suggestions I would be most appreciative. Thanks in advance,
__Chris
Hey @cmikkelsen
Welcome to the Postman community! 
What does your global variable look like? Can you console.log(regex)
and show what that returns?
I’ve seen this error message before but I can’t remember why it’s happening. I’m sure in was something to do with the way the regex string is inside that match()
function…but I might be wrong. 
The regex in the variable is: /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/. When it is returned by then pm.globals.get() call it shows in the log as “/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/”.
I think because it would be returned from the variable as a string for example - "regex_code"
The match()
function wouldn’t recognise it as regex. You would need to strip out the quote marks.
1 Like
Thanks. I will give that a shot & see if it works.
Figured it out. Essentially I used the JS RegEx class to generate a regex based on the string I have stored in my global variable. So my code now looks like this:
let tds_regex = new RegExp(pm.globals.get('timeDateStamp_regex'));
pm.expect(jsonData.value[0]['CreatedDt']).to.match(tds_regex);
In addition I found out that the RegEx class adds a “/” to the beginning & end of the string you create it with so I had to change my original regex string from /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/
to \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}
.
Not sure it is the best way but it is working for me.
Thanks @danny-dainton for your suggestion. Looking into that lead to this.
3 Likes