Home > Blockchain >  Why is the test with no arguments failing in Typescript?
Why is the test with no arguments failing in Typescript?

Time:10-19

export function twoFer( arg : string ): string 
{
  if( arg !== "")
  {
    return "One for "   arg   ", one for me.";
  }
    return "One for you, one for me." ;
}

I am not able to understand what am I doing wrong. This is failing in the case when no argument is supplied.

describe('TwoFer', () => {
  it('no name given', () => {
    const expected = 'One for you, one for me.'
    expect(twoFer()).toEqual(expected)
  })
})

Output:

TEST FAILURE
Error: expect(received).toEqual(expected) // deep equality

Expected: "One for you, one for me."
Received: "One for undefined, one for me."

https://exercism.org/tracks/typescript/exercises/two-fer

CodePudding user response:

A string parameter not specified doesn't contain an empty string; it contains undefined. You would want something like this:

export function twoFer(arg?: string): string
{
    if(typeof arg !== "undefined") {
        return "One for "   arg   ", one for me.";
    }
    return "One for you, one for me.";
}

UPDATE:

Alternatively, you can make arg a parameter with a default value instead to reduce redundancy.

export function twoFer(arg = "you"): string
{
    return "One for "   arg   ", one for me.";
}
  • Related