Lin Du
Lin Du

Reputation: 102367

Jest, how to compare two strings with different format?

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?

Upvotes: 7

Views: 16779

Answers (2)

Hugo B. S. Benedicto
Hugo B. S. Benedicto

Reputation: 191

Instead of removing all the white spaces from the string, another good way to fix this problem is to format the strings with the same pattern. I fixed this problem importing the format function from prettier module:

import {expect} from '@jest/globals'
import {format} from 'prettier'

const htmlStr = `
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample</title>
  </head>
  <body>
    <div>Test</div>
  </body>
  </html>
`

const expectedHtmlStr = `
            <!DOCTYPE html>
            <html lang="en">
            <head>
              <meta charset="UTF-8">
              <meta http-equiv="X-UA-Compatible" content="IE=edge">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <title>Sample</title>
            </head>
            <body>
              <div>Test</div>
            </body>
            </html>
`

const formatStmt = (str: string) => format(str, { parser: 'html' })

// The test passes
expect(formatStmt(htmlStr)).toBe(formatStmt(expectedHtmlStr))

Upvotes: 0

Lin Du
Lin Du

Reputation: 102367

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, ''));

Upvotes: 7

Related Questions