简体   繁体   中英

How to write angular unit test for function and switch case

extractValue(exemptionLevel: string, exemptionValue: any): string {
switch(exemptionLevel) {
  case "C": return exemptionValue.isoCountryCode.toString();
  case "R": return exemptionValue.districtNumber.toString();
  case "D": return exemptionValue.divisionCode.toString();
  case "T": return exemptionValue.terminalNumber.toString();
}

}

i tried below

it('expected value extractValue() c', () => {
component.extractValue('C','isoCountry');
expect('C').toEqual('isoCountry')

// expect(component.extractValue(expectedLevel[0], exemptionValue.isoCountryCode)).toHaveBeenCalled();

});

it showing error TypeError: Cannot read property 'toString' of undefined

You are sending a string parameter to the function and you are expecting to access its isoCountryCode property, which will always be undefined. You have to provide the tested function with exemptionValue mock.

it('expected value extractValue() c', () => {
  const isoCountryMockResult = 'someResult';
  const exemptionValue = { isoCountryCode: isoCountryMockResult } // define your mock
  component.extractValue('C', exemptionValue);
  expect('C').toEqual(isoCountryMockResult)
}

This should work, but you have to adjust it to your needs

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