How to check the type of a unit test value using Jest?

Asked

Viewed 36 times

1

I have a function that returns an object with two properties: name and id, where name will receive its value per parameter and id is generated automatically by Date.now().

My goal is to create a test in Jest that checks if the id value is of the numeric type, since I can’t compare its exact value

The object creation function:

const createNewTodo = (addTodoInputValue) => {
  const newTodo = {
    id: Date.now(),
    name: addTodoInputValue
  }

  return newTodo
}

1 answer

1


If you want to test the type of some value in Javascript, nothing prevents you from making an assertive using the operator typeof.

So, for example, to check if any value <value> is numerical type, it is made:

assert(typeof <value> === 'number');

Using the Jest API:

expect(typeof <value>).toBe('number');

In his example:

const todo = createNewTodo('Learn Jest');
expect(typeof todo.id).toBe('number'); // <-- Asserção aqui.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.