【问题标题】:Jest, how to compare two strings with different format?开玩笑,如何比较两个不同格式的字符串?
【发布时间】:2019-01-07 09:11:40
【问题描述】:

我使用Jest 编写单元测试。

这是测试输出:

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
      }
    "

此测试失败。虽然这两个字符串的内容相同,但格式化程序不同。

我希望通过这个单元测试。我该怎么做?

【问题讨论】:

  • 只是开头和结尾的空格不同还是中间也不同?在比较之前,您可以尝试在字符串上使用.trim()
  • 不,我不想使用RegExpstring 之类的方法来处理我的字符串。
  • 如果格式故意不同,那么精确的字符串匹配可能不起作用。您将不得不找到一种不同的方法来进行比较。您可以手动遍历每个字符,忽略空格,并确保每个字符串具有相同的字符。如果格式没有故意不同,那么解决方案可能是让创建它们的任何东西都使用相同的格式。
  • @lemieuxster 感谢您的建议。我找到了和你一样的方法。

标签: javascript jestjs


【解决方案1】:

也许你的函数的返回值是这样的:

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

但是对于单元测试,我们要忽略字符串的格式化程序。方法是去掉字符串的所有空格,以便与内容进行比较。

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

【讨论】:

    【解决方案2】:

    解决这个问题的另一个好方法是用相同的模式格式化字符串,而不是从字符串中删除所有空格。我从prettier 模块导入format 函数修复了这个问题:

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

    【讨论】:

      猜你喜欢
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 2015-11-26
      相关资源
      最近更新 更多