【问题标题】:How to assert a string containing some fixed words along with some variable numbers?如何断言包含一些固定单词和一些可变数字的字符串?
【发布时间】:2020-10-12 07:17:15
【问题描述】:

我想断言:“30 天内有 10 个自动结果”,其中 10 和 30 来自 API 调用,因此可以是任何值。

我正在寻找 Jest 断言,例如:

expect(pageobject.webelement.getText()).toEqual("10 Automated results in 30 days"); // but it fails some other day because 10 & 30 can be any number at any point of time.

我怎样才能断言这一点,以便我的代码应该寻找精确的字符串,但指定位置的任何数字除外?

【问题讨论】:

标签: javascript jestjs automated-tests mocha.js webdriver-io


【解决方案1】:

你可以像这样使用正则表达式来匹配字符串,

describe('stringMatching', () => {
   const expected = /[0-9]* Automated results in [0-9]* days/;

   it('matches if the received value does not match the expected regex', () => {
       expect(pageobject.webelement.getText()).toMatch(expected);
   });
});

【讨论】:

  • 感谢@sabir.alam 的回复。尽管使用 .toEqual 失败了,但我使用了 toMatch 并且它有效。顺便说一句,你能告诉我 [0-9] 中的星号是什么意思*
  • 我的错,我复制了你的那部分代码并错过了 toEqual 部分。 :p更新了我的答案。那个 * 意味着它将在那个地方寻找 0 个或更多的数字。如果我只输入 [0-9] 则意味着只有 1 个数字。
  • 嘿@sabir.alam 如果我想在下面断言怎么办:“30 天内 10 个自动化结果”;我的意思是 10 点后换行。提前致谢
  • 我相信您需要在您希望新行所在的位置添加[\r\n]。 \r 用于支持 windows 和经典的 mac 系统。您可以在此线程中找到更详细的答案:stackoverflow.com/questions/1979884/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-12
  • 2020-01-13
  • 2022-01-13
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 2015-05-31
相关资源
最近更新 更多