how to avoid partial hit in codecov for a ternary assignment

Viewed 219

I have a vue function that returns an array of strings

1 selectStyles (): string[] {
2  const baseStyles = ['selected-label', 'px-4']
3  const placeholderStyle = this.internalValue?.length === 0 ? 'text-gray-400' : 'text-black'
4
5  return [...baseStyles, placeholderStyle]
6 },

And I have three jest tests cases testing for

  1. if internalValue has a value and it's therefore its length is !0
  2. if internalValue is an empty array and therefore its length is 0
  3. if internalValue is undefined, undefined === 0 is false and therefore second condition is assigned

And yet codecov says that line 3 is a partial hit?

Any idea why?

I read this great response concerning an if statement in python and the results of that, but I don't think it answers my question.

Here are my test cases:

  it('selectStyles', () => {
    expect(
      Select.computed.selectStyles.call({
        internalValue: []
      })
    ).toEqual(['selected-label', 'px-4', 'text-gray-400'])

    expect(
      Select.computed.selectStyles.call({
        internalValue: ['some opt selected']
      })
    ).toEqual(['selected-label', 'px-4', 'text-black'])

    expect(
      Select.computed.selectStyles.call({
        internalValue: undefined, // unlikely
      })
    ).toEqual(['selected-label', 'px-4', 'text-black'])
  })

Tyia!

1 Answers

You can use Nullish coalescing operator (??) to check if internalValue is undefined or not as this operator returns its right-hand side operand when its left-hand side operand is null or undefined.

// Here if this.internalValue is undefined we are assigning it with an empty array.
this.internalValue = this.internalValue ?? []

Your logic will be like this :

selectStyles (): string[] {
  const baseStyles = ['selected-label', 'px-4']
  this.internalValue = this.internalValue ?? []
  const placeholderStyle = this.internalValue?.length === 0 ? 'text-gray-400' : 'text-black'
  return [...baseStyles, placeholderStyle]
}

I just gave my thought as per your problem statement. You can do modifications as per the actual code you have.

Related