简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM