Override nested child element with spread operator in javascript

For the following req object there is a need to override the stackoverflowId attribute in a jest test

const req = {
  body: {
    _id: '123',
    name: 'Codever',
    location: 'https://www.codever.dev',
    language: 'en',
    description: 'This is a test bookmark',
    tags: ['test'],
    public: true,
    stackoverflowQuestionId: null
  },
  params: {
    userId: '456',
  },
};

Project: codever - File: bookmark-request.mapper.test.js

Here is how to achieve that with the spread operator

      {...req,
        body : {
        ...req.body,
          stackoverflowQuestionId: 123456
        }
      }

The complete function where this is used is shown below:

 test.each([
    [
      'should set stackoverflowQuestionId if it is provided',
      {...req,
        body : {
        ...req.body,
          stackoverflowQuestionId: 123456
        }
      },
      new Bookmark({
        _id: '123',
        name: 'Codever',
        location: 'https://www.codever.dev',
        language: 'en',
        description: 'This is a test bookmark',
        descriptionHtml: '<p>This is a test bookmark</p>',
        tags: ['test'],
        public: true,
        userId: '456',
        likeCount: 0,
        youtubeVideoId: null,
        stackoverflowQuestionId: 123456,
      })
    ],
  ])('%s', (testname, req, expectedBookmark) => {
    const resultBookmark = bookmarkRequestMapper.toBookmark(req);

    expect({...resultBookmark.toObject(), _id: {}}).toEqual({...expectedBookmark.toObject(), _id: {}});
    expect(showdown.Converter).toHaveBeenCalledTimes(1);
    expect(showdown.Converter().makeHtml).toHaveBeenCalledTimes(1);
    expect(showdown.Converter().makeHtml).toHaveBeenCalledWith('This is a test bookmark');
  });

Reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax


Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏

Subscribe to our newsletter for more code resources and news

Adrian Matei (aka adixchen)

Adrian Matei (aka adixchen)
Life force expressing itself as a coding capable human being

routerLink with query params in Angular html template

routerLink with query params in Angular html template code snippet Continue reading