Home > Software design >  How to mock data when writing unit tests for a function that relies on said data?
How to mock data when writing unit tests for a function that relies on said data?

Time:12-16

const data = [1,2,3,4]

function parse(index){
  return data[index]
}

Say I have a function parse that grabs something from data based on the input. What would be the best way to mock the data in our test file?

I've looked into jest.fn() and spying but it looks like these are more for mocking functions. Is there any built in method to mock the dataset and direct the function to that mock data rather than the actual data? I've also considered refactoring the function to take the data as an input so that we can pass it the mock data in our test file but I'm curious if there's any other way.

CodePudding user response:

Ok, you have a function that relies on some initial things like data and an input index. In order to unit test something, you need to inject all external dependencies in the unit. I will propose to you two approaches

Approach 1: defined your unit as a class and inject external dependencies in a constructor.


const defaultData = [1,2,3,4];

class Parser {
  //if constructor argument is not provided it will take the default data
  constructor(data = defaultData) {
    this.data = data;
  }

  parse(index) {
    return data[index]
  }
}

// usage

const pareser1 = new Parser(); //this will initialize it with default data
const pareser2 = new Parser([ 67,8, 15 ]); //you can also pass data override

Approach 2: define your unit as the function itself and inject external dependencies as in the function params. This is not very readable if the dependencies are too many

const defaultData = [1,2,3,4];

//second optional parameter with default value
function parse(index, data = defaultData){
  return data[index]
}


//usage

const result1 = parse(5) //this will call it with the defautlData
const result2 = parese(5, [4,78,9,10]) // we can inject the data array

  • Related