| data[key].trim() ...

问题描述 投票:0回答:1
You should pass to

a reference to a function that when called throws an error

e.g.

const validatorMethod = (data) => {
  const validationResult = Object.keys(data)
    .map((key) => {
      if (!data[key] || data[key].trim() === '') {
        return key;
      }
      return true;
    });
  if (validationResult.filter((prop) => prop === true).length !== data.length) {
    return validationResult.filter((prop) => prop !== true);
  }
  return true;
};

module.exports = {
  userObjectFactory (data) {
    console.log(data);
    const invalidKeys = validatorMethod(data);
    if (invalidKeys.length === true) {
      console.log(1);
      return data;
    }
    console.log(2);
    throw new Error('One of passed properties is empty');
  },
};

or

const userTemplate = {
  id: 1,
  email: '[email protected]',
  password: 'zaq1@WSX',
  fullName: 'full name',
  location: 'location',
  isLookingForWork: false,
};
describe('factory should throw error on undefined, null, or ""', () => {
  it('should throw an error if some inputs are undefined', () => {
    const userWithUndefinedProperty = userTemplate;
    userWithUndefinedProperty.id = undefined;
    userWithUndefinedProperty.password = undefined;

    assert.throws(
      userObjectFactory(
        userWithUndefinedProperty, new Error('One of passed properties is empty'), // also tried "Error" and "Error('One of passed properties is empty')" without the "new"
      ),
    );
  });
});

  0 passing (68ms)
  2 failing

  1) testing UserObjectFactory
       should return an object with correct data:
     Error: One of passed properties is empty
      at userObjectFactory (src\user\UserObjectFactory.js:2:1646)
      at Context.it (test\user\UserObjectFactory.test.js:33:18)

  2) testing UserObjectFactory
       factory should throw error on undefined, null, or ""
         should throw an error if some inputs are undefined:
     Error: One of passed properties is empty
      at userObjectFactory (src\user\UserObjectFactory.js:2:1646)
      at Context.it (test\user\UserObjectFactory.test.js:26:9)
我正在尝试测试错误抛出。
javascript node.js unit-testing mocha chai
1个回答
1
投票

输出assert.throws

const thisIsAFunctionThatIsSupposedToThrowWhenCalled = () =>
  userObjectFactory(
    userWithUndefinedProperty,
    new Error("One of passed properties is empty") // also tried "Error" and "Error('One of passed properties is empty')" without the "new"
  );

assert.throws(thisIsAFunctionThatIsSupposedToThrowWhenCalled);

我试图测试错误的抛出。下面是我的代码 const validatorMethod = (data) => { const validationResult = Object.keys(data) .map((key) => { if (!data[key]

© www.soinside.com 2019 - 2024. All rights reserved.