Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing arguments as an object in function but in unit tests it is undefined

I am trying to understand why passing function arguments as an object works in my code, but not in my unit test. For example

const arg1 = "foo";
const arg2 = "bar";

function myFunc({arg1, arg2}) {
    console.log(arg1); // "foo"
    console.log(arg2); // "bar"
    return { "name": arg1, "colour": arg2 };
}

Above works just as expected. However trying to test comes back as undefined.

describe("myFunc", () => {
    const mockArg1 = "mockFoo";
    const mockArg2 = "mockBar";

    it("should return an object with name set as arg1", () => {
        expect(
            myFunc({
              mockArg1,
              mockArg2
            }).name
        ).toBe("mockFoo");
    });
});

When I run the above test, the values of mockArg1 and mockArg2 are undefined in the function, even though I’ve passed them through inside an object exactly as my function expects.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What am I doing wrong in the syntax of this expect call of myFunc?

>Solution :

You need to call the myFunc like this:

describe("myFunc", () => {
    const mockArg1 = "mockFoo";
    const mockArg2 = "mockBar";

    it("should return an object with name set as arg1", () => {
        expect(
            myFunc({
              arg1: mockArg1, // !!!
              arg2: mockArg2  // !!!
            }).name
        ).toBe("mockFoo");
    });
});

as you expect the arguments to be called arg1 and arg2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading