how to use the stubarray function from lodash in javascript

The _.stubArray() function from Lodash returns a new empty array. This can be useful as a default value or placeholder for functions that expect an array to be passed in as an argument.

To use it in your code, you first need to install Lodash by running the following command in your terminal:

index.tsx
npm install lodash
19 chars
2 lines

Then, you can use it like this:

index.tsx
const _ = require('lodash');

function myFunction(items = _.stubArray()) {
  // `items` will be an array, defaulted to an empty array if none is passed in
  console.log(items);
}

myFunction(); // outputs: []
myFunction(['item1', 'item2']); // outputs: ['item1', 'item2']
272 chars
10 lines

This function is commonly used in testing scenarios to create a mock implementation of a function that expects an array to be passed in. Here is an example:

index.tsx
const _ = require('lodash');

function doSomething(items = _.stubArray()) {
  // do something with `items`
}

describe('doSomething', () => {
  it('should accept an empty array by default', () => {
    doSomething(); // makes sure function does not throw an error
  });

  it('should accept non-empty array', () => {
    const items = ['item1', 'item2'];
    doSomething(items); // makes sure function does not throw an error
  });
});
436 chars
17 lines

gistlibby LogSnag