Jest: Expect a String Result to be Numeric

JavaScript unit tests in Jest may need to assert that a string result from a function is numeric, i.e. a string containing only numbers.

Since we do not have a convenient matcher like toBeNumeric(), none of the ways currently looks quite perfect, but several possible ways are below, some more readable than others.

First, suppose we have a simple function to return a numeric string:

func.js:

const func = () => {
  return "12345"
}

module.exports = func

Then our unit test in the first form: using toBeNaN(), negated, combined together with the Number constructor:

func.spec.js:

const func = require('./func')

describe('numeric string result', () => {
  it('should be numeric', () => {
    expect(Number(func())).not.toBeNaN() // numeric
  })
})

 

The above is somewhat clear, but the following may be more readable to some:

const func = require('./func')

describe('numeric string result', () => {
  it('should be numeric', () => {
    expect(Number.isNaN(func())).toBe(false)
  })
})

 

Another way is to use a Regular Expression (regex) to expect a numeric string, however, this is most readable for integers:

const func = require('./func')

describe('numeric string result', () => {
  it('should be numeric', () => {
    expect(func()).toMatch(/[0-9]+/) // string of integers
  })
})

The regex would become more complex if we wanted to accept any kind of numeric notation, including real numbers or large numbers with exponential notation, for example.

Perhaps the highest readability is achieved by breaking out the numeric check into its own convenience function, as below:

const func = require('./func')

const isNumeric = (string) => {
  return !Number.isNaN(string)
} 

describe('numeric string result', () => {
  it('should be numeric', () => {
    expect(isNumeric(func())).toBe(true)
  })
})

Leave a Reply

Your email address will not be published. Required fields are marked *