Search code examples
jestjsstring-comparisonts-jest

Jest expect.stringMatching() SyntaxError: Invalid regular expression


We have: A function that returns random values (In our case, crypto -> aes)

What do we want to do? Compare that this string is not equal to the past


We mean that the object in which the string is located is large enough, so we compare the string inside the object, and not separately


How do we compare?

const oldCiper = "oldRandom+String-/FromAny==Characters";

// Pay attention to the plus sign at the beginning of a new line
const newCiper = "+newRandomString-\From/Any==Charac+ters";

// We will get an error here 
// SyntaxError: Invalid regular expression...
expect({cipher: oldCiper }).toEqual({cipher: expect.not.stringMatching(newCiper)})

Full Error: SyntaxError: Invalid regular expression: /+newRandomString-\From/Any==Charac+ters/: Nothing to repeat


Solution

  • Solution

    Use stringContaining instead of stringMatching

    const oldCiper = "oldRandom+String-/FromAny==Characters";
    
    const newCiper = "+newRandomString-\From/Any==Charac+ters";
    
    expect({cipher: oldCiper }).toEqual({cipher: expect.not.stringContaining(newCiper)})
    

    The first character for an error can be not only a plus, but also "W", "L", etc.