Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest, how to compare two strings with different format?

Tags:

I use Jest write unit tests.

Here is the test output:

expect(string).toContain(value)

Expected string:
  "      input CreateBookInput {
        title: String
        author: String!
      }
      input UpdateBookInput {
        title: String
        author: String
      }
    "
To contain value:
  "
      input CreateBookInput {
        title: String
        author: String!
      }
      input UpdateBookInput {
        title: String
        author: String
      }
    "

This test is failed. Though these two strings' content are same, but the formatter is different.

I want this unit test pass. How can I do this?

like image 836
slideshowp2 Avatar asked Jul 31 '18 04:07

slideshowp2


People also ask

What are the 3 ways to compare two string objects?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.

Can you use .equals to compare strings?

Definition and UsageThe equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.

How do I compare the contents of two strings?

Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.

How do you compare characters in two strings?

You can compare two Strings in Java using the compareTo() method, equals() method or == operator. The compareTo() method compares two strings. The comparison is based on the Unicode value of each character in the strings.


1 Answers

Maybe the return value of your function like this:

const expectValue = `
  input CreateBookInput {
    title: String
    author: String!
  }
  input UpdateBookInput {
    title: String
    author: String
  }
`;

But for the unit test, we want to ignore the formatter of the string. The way is to remove all whitespaces of the string so that they can be compared with content.

expect(actualValue.replace(/\s/g, '')).toEqual(expectValue.replace(/\s/g, ''));

like image 187
slideshowp2 Avatar answered Sep 28 '22 18:09

slideshowp2