0

I want to assert: "10 Automated results in 30 days" in which 10 & 30 is coming from API call so it can be anything.

I am looking for Jest assertions, for example:

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.

How can I assert this such that my code should look for exact string but except any number at specified location?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Yash
  • 121
  • 7
  • Regular expression ([`toMatch`](https://jestjs.io/docs/en/expect.html#tomatchregexporstring))? Or control the test context more closely so you can know (or set) what the values are. – jonrsharpe Oct 12 '20 at 07:21
  • use [https://jestjs.io/docs/en/expect#tomatchregexporstring](https://jestjs.io/docs/en/expect#tomatchregexporstring) – Lin Du Oct 12 '20 at 07:23

1 Answers1

1

You can use regex to match the string like this,

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);
   });
});
Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30
  • Thanks @sabir.alam for your reply. Although it is failing with .toEqual instead i used toMatch and it worked. BTW can you tell me what star mean in [0-9]* – Yash Oct 12 '20 at 07:55
  • My bad, I copied that part of your code and missed the toEqual part. :p Updated my answer. That * means it will be looking for 0 or more digits in that place. If I would put [0-9] only it would mean only 1 digit. – Md Sabbir Alam Oct 12 '20 at 08:03
  • Hey @sabir.alam what if i want to assert below: "10 Automated results in 30 days"; i mean new line after 10. Thanks in advance – Yash Oct 12 '20 at 09:28
  • I believe you need to add `[\r\n]` where you want the new line to be. The \r is for supporting windows and classic mac systems. You can find more detailed answer in this thread: https://stackoverflow.com/questions/1979884/how-to-use-javascript-regex-over-multiple-lines – Md Sabbir Alam Oct 12 '20 at 10:08