skip to Main Content

I have this helper

const getPrefix = ({ value }: MyValue) => {
  switch (value) {
    case 'Value one':
      return 'Prefix one';
    case 'Value two':
      return 'Prefix two';
    default:
      return null;
  }
};

However my test is failing:

describe('getPrefix', () => {
  it('should generate prefix correctly', () => {
    expect(
      getPrefix({
        title: 'Test title',
        value: '',
      })
    ).toBe('Test title');
  });
});

It says:

Expected: "Test title"
Received: "Test title null"

I adds null?

How to fix this?

2

Answers


  1. If I understand correctly, your code is actually looking on the value of value which in your case is ''. Which means the default case is correctly executed. But the code you provided should not append anything anywhere, the function should simply return null and the test would fail with:

    Expected: "Test title"
    Received: null
    

    Please see if your code examples are correct.

    Login or Signup to reply.
  2. If you are using the + operator or template string literals, and you have a null value E.G.

    let title = 'SWE'
    let subtitle = null
    let fullTitle = title + subtitle 
    // `${title} ${subtitle}` will have the same effect
    console.log(fullTitle) // SWE null
    

    The problem with using null like this is that it has a toString method meaning that if you coerce it to with template literals or + operator and the first operand is a string it coerces null into a ‘null’ as opposed to it being blank or no-value.

    The test did its job and found the error as a previous answer suggested if the expected behavior is to return a blank or nothing then you want to return an empty string ''

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search