Home > Software design >  Array values stays the same in Unit test after side effect function. - Mocha
Array values stays the same in Unit test after side effect function. - Mocha

Time:11-04

I'm trying to change Array(filter out Values). I'm filtering out Array values inside of function, the Array changes itself, but Array in Test case stays unchanged. The project is written in Typescript, and tested with Mocha.

I've been trying to filter out values ['.jgp', '.png] from Array. Logged value shows, that function works properly.

import 'mocha';

import { expect } from "chai";


import Filter from "../src/Filter";

let filter = new Filter("Websites Filter");

describe("Filter", function () {

describe("filterOut", () =\> {
it("Should return array as specified conditions says", function () {
let png_jpg_filter = function(el){
return !el.endsWith(".png") && !el.endsWith(".jpg");
};

      filter.addFilter("png_jpg_filter", png_jpg_filter);
    
      let arrToFilter = [".png", ".jpg", ".gif"]; // < this Array
    
      filter.filterOut(arrToFilter); // <- this Function
    
      expect(arrToFilter).equals([".gif"]);
    });

});

});

    filterOut(toFilterOut: Array<string>): void{
        this.filterCallbacks.forEach(callback => {
            toFilterOut = toFilterOut.filter(el => callback(el))
        })
        console.log("filtered out:");
        console.log(typeof toFilterOut);
        console.log(toFilterOut);
    }

And Test Answer:


filtered out:
object
\[ '.gif' \] \< After Filtering
1) Should return array as specified conditions says

1 passing (37ms)
1 failing

1) Filter
   filterOut
   Should return array as specified conditions says:

   AssertionError: expected \[ Array(4) \] to equal \[ '.gif' \]

     expected - actual

   \[

   - ".png"
   - ".jpg"
     ".gif"
     \]

CodePudding user response:

I've found answer to my question. There was created new reference, when I had made assignment inside the function. Better description:

https://medium.com/@naveenkarippai/learning-how-references-work-in-javascript-a066a4e15600

Under "How references work when values are passed as function parameters?"

  • Related