How to set up an assertion to verify value of an element on JS-Jest?

Can I set up an assertion to verify value of an element on Jest?

Hi Devan,

To set up an assertion on Jest, you can use the following script:

globalThis.assert = (()=> {
  class AssertionError extends Error {
    constructor(message) {
      super(message);
      this.name = 'AssertionError';
    }
  }
  let config = {
    async: true,
    silent: false
  };
  function assert(condition, message = undefined) {
    if (!condition) {
      if (config.silent) {
        //NOOP
      } else if (config.async) {
        console.assert(condition, message || 'assert');
      } else {
        throw new AssertionError(message || 'assertion failed');
      }
    }
  }
  assert.config = config;
  return assert;
})();


/* global assert */
Object.assign(assert.config, {
  // silent: true, // to disable assertion validation
  async: false, // to validate assertion synchronously (will interrupt if assertion failed, like Java's)
});

let items = [
  {id: 1},
  {id: 2},
  {id: 3}
];
function deleteItem(item) {
  let index = items.findIndex((e)=> e.id === item.id);
  assert(index > -1, `index should be >=0, the item(id=${item.id}) to be deleted doesn't exist, or was already deleted`);
  items.splice(index, 1);
}

console.log('begin');
deleteItem({id: 1});
deleteItem({id: 1});
console.log('end');"