Katerin1122
Katerin1122

Reputation: 75

Jest test method

I don't have so much experience with Jest and I have some issues testing the following javascript method:

const parseResults = (items) => {
  const results = [];
  const itemsLength = items.length;
  for (let i = 0; i < itemsLength; i += 1) {
    const element = items[i];
    if (element.status === "fulfilled") {
      if (Array.isArray(element.value)) {
        results.push(...element.value);
      } else {
        results.push(element.value);
      }
    } else {
      logger.error(`${element.reason}`);
    }
  }
  return results;
};

and so far, my test is this:

describe("parseResults", () => {
  it("should ", () => {
    const items = [{ element: "status", value: "testValue" }];

    const result = parseResultsAndErrors(items);

    expect(result).toBe();
  });
});

On Received it gives me an empty []. I think something is wrong here.. anyone knows how to write this test and how should I write the expect ?

Upvotes: 1

Views: 272

Answers (1)

Thatkookooguy
Thatkookooguy

Reputation: 7002

toBe is usually used with a value to check that result is equal to something you expect. So the usage is like so:

expect(results).toBe([{ value: 'hello' }])

But that tests actual equality (equality by reference), and you want to check equality by value.

With any unit-test framework (this is agnostic to the framework itself), you want to cover all the scenarios your function covers.

For you function it's

  • element.status === "fulfilled" and Array.isArray(element.value)
  • element.status === "fulfilled" and !Array.isArray(element.value)
  • element.status !== "fulfilled"

so a test would look something like this:

describe("parseResults", () => {
  it('should add only fullfiled item', () => {
    const items = [
      {
        status: 'fulfilled',
        value: 'singleTestValue'
      },
      {
        status: 'fulfilled',
        value: [ 'arrayValue1', 'arrayValue2' ]
      },
      {
        status: 'pizza',
        value: 'notIncluded'
      }
    ];

    const result = parseResults(items);

    expect(result.length).toBe(3);
    expect(result).toContain('singleTestValue');
    expect(result).toContain('arrayValue1');
    expect(result).toContain('arrayValue2');
    expect(result).not.toContain('notIncluded');
    // expect(result.sort())
    //   .toEqual([
    //     'singleTestValue',
    //     'arrayValue1',
    //     'arrayValue2'
    //   ].sort());
  });
});

We have all the cases the function can handle in that test. so we covered everything in the function. The only thing else you can test is that the logger was called.

You can also test that the entire result array equals another array, but you have to .sort() them in order to make sure the order is the same. Also, doing a toEqual won't work on array of objects so check the documentation if you need a scenario like that as well.

Upvotes: 1

Related Questions