Jest testing and changing attribute value using JavaScript

1.4k views Asked by At

I am trying to write a test using Jest. There is already a similar test testing if an attribute that is calculated gives a tooltip saying so. Now I am trying to test if an attribute that has an inline reference gives a tooltip saying so. There is added "hasInlineRef: false" to the AnalysisList. It has to be false, else it will overwrite the previous test. But when initializing it for my test, I would like to change it so hasInlineRef = true, which should make the test pass. I suspect it is my very limited knowledge of JavaScript that fails me here.

describe("AnalysisList", () => {
    const analysisList: Array<AnalysisListItem> = [{
        value: "AAAAAA",
        count: 23456,
        capped: false,
        hasInlineRef: false,
        dbValue: "AAAAAA"
    }, {
        value: "AA",
        count: 800,
        capped: true,
        hasInlineRef: false,
        dbValue: "AA"
    }];

Below I would like to initialize the AnalysisList with hasInlineRef = true.

    test("should have inline reference attribute tooltip when attribute is hasInlineRef", () => {
        const component = mount(<AnalysisList analysisList={analysisList} onSearch={jest.fn()}  />);
        const tooltip = component.find("Tooltip").first().simulate("click");
        expect(tooltip.props().title).toContain("inlineRefAttributesNoSearch");
    });

1

There are 1 answers

1
skyboyer On BEST ANSWER

Answering question "how to change single property inside the array?" has straightforward answer:

analysisList[0].hasInlineRef = true;

Here we can see accessing array's item by its index([0]) and accessing property by its name hasInlineRef.

Need to do the same for all items in array makes us either using loops:

for(item in analysisList) {
    item.hasInlineRef = true;
} 

Or using methods available for any Array:

analysisList.forEach(item => {
    item.hasInlineRef = true;
})

More on working with arrays in JS: https://www.w3schools.com/js/js_arrays.asp

Thanks to accessing by reference original analysisList changes as well as we transform any of its item one-by-one.

But. If we look at the very start point I believe it's bad idea to mutate test data per-test case. Why?

  1. tests become harder to maintain since you never know if you can remove/add/change data or it will break some test just because data mutation will no longer work(at the same time component will continue work! so test's failure will say nothing)
  2. tests themselves become less reliable: changing ordering would lead to different results!

If you don't like having huge data payload in test's code you may move it into separate data_with_some_nuances.json, another_data_payload.json and load them into test with the help of import statement.