简体   繁体   中英

jest unit test javascript

I have a unit test I am trying check the field but cannot find anything in the jest documentation to ignore the one value in this case, randomNumber.

const expected = [
  {
    model: 'string',
    type: 'string',
    randomNumber: 43,
    name: 'string',
  },
]

The random number changes every test so I can't hard code the test to check that number. I would like to test to make sure the expected array has all of the fields, but ignore the values.

const requiredKeys = ["model", "type", "randomNumber", "name"];

const actual = [
    {
      model: 'string',
      type: 'string',
      randomNumber: 43,
      name: 'string',
    },
    {    
      type: 'string',
      randomNumber: 43,
      name: 'string',
  },
]

actual.forEach(x => {
  const keys = Object.keys(x);
  const hasAllKeys = requiredKeys.every(key => keys.includes(key));

  expect(hasAllkeys).toBeTruthy();
});

You can do something along the lines of this

const data =  {
    model: 'string',
    type: 'string',
    randomNumber: 43,
    name: 'string',
 }

const dataExpected = {
    model: 'string',
    type: 'string',
    name: 'string',
}

const {randomNumber, ...randomNumOmittedData} = data;

expect(randomNumOmittedData).toEqual(dataExpected);


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM