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

Time:09-27

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.

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

CodePudding user response:

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

  • Related