20

What is the best way to ensure a value is found (e.g not an empty string) using e2e testing, my example simply matches the text itself, I want to count the string length & ensure it isn't 0.

describe 'Device Details', ->
device = ionic.Platform.device()
details =
'deviceManufacturer': $('#deviceManufacturer'),
'deviceModel': $('#deviceModel')

it 'Device Manufacturer must not be empty', ->
  expect(details.deviceModel.getText()).toEqual '10'
Zabs
  • 13,852
  • 45
  • 173
  • 297

3 Answers3

23

try not.toBe('') to check not empty

expect(details.deviceModel.getText()).not.toBe(''); 

=== other cases ====

 expect('hello world').not.toBe(''); //true 
 expect('').toBe(''); //true
Surendra Jnawali
  • 3,190
  • 5
  • 28
  • 44
  • This is the best answer here. Readable to purpose. Also handles undefined cases well. – PathToLife Aug 02 '21 at 03:06
  • 1
    Bad answer. Many things are not equal to an empty string. Numbers, booleans, instances of virtually anything. If you want to use this for whatever reason, it has to be preceded by a type check. – Victor Schröder Sep 16 '21 at 11:40
  • 1
    That's too strong a statement, given the title implies it's known to be string, and the question body's example method can only return a string. Under those assumptions, this is the simplest and easiest answer. It's an important caveat in the general (and my) case though, so I submitted an edit to make the limitation explicit and add the necessary additional check to assert on the type. – John Neuhaus Jan 03 '22 at 22:46
21

There are different ways to do that but I prefer toBeNonEmptyString() from the jasmine-matchers package - simple and readable:

expect(details.deviceModel.getText()).toBeNonEmptyString();
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 2
    installing a package while nice, may be over optimisation. I find @Surendra Janwali's answer equally succinct in readability: expect().not.toBe(''); but not require a package – PathToLife Aug 02 '21 at 03:04
18

Without using jasmine-matchers.

   details.deviceModel.getText().then(function(text) {
      expect(text.length).not.toEqual(0)
    });

See comment below for caveat(s)

KCaradonna
  • 760
  • 6
  • 13
  • thanks i had some issues with the jasmine-matchers so this way is very useful also – Zabs Feb 25 '16 at 10:45
  • 3
    It may not be an issue but note that this test will pass for everything except primitives, empty strings, and empty arrays. an object where `.length` is `undefined` for example would pass this test as that is not equal to zero. Hope this helps, again, it may not be an issue for your particular case. – Jamie Mason Nov 07 '16 at 16:29