Vue testing with Jest: Mock window.location

The bottom line is that you can not mock window.location, BUT you can delete it and create your own to use in test. I will here show one example of how this can be achived:

describe('methodUnderTest', () => {
  // Save current windows.location
  const oldWindowLocation = window.location;
  // Some mocked value
  const mockedUrl = 'https://blog.niklasottosson.com';

  beforeEach(() => {
    // Remove windows.location so that we can create a new
    delete window.location;

    // Create a new mutable window.location
    window.location = Object.defineProperties(
      {},
       {   // copy all properties from the old window.location
        ...Object.getOwnPropertyDescriptors(oldWindowLocation),
        // Start mocking...
        assign: {
           configurable: true,
           value: jest.fn()
        },
        href: {
            configurable: true,
            value: mockedUrl
        }
     );
  });

  afterEach(() => {
    // Restore window.location
    window.location = oldWindowLocation;
  });

  // Start creating your tests...
  it('should...', () => {
    ...
  } 

Tested on OSX 10.15.7, Vue v2.6.12 and Jest v26.0.14

Spring Boot: Map JSON body with root node in @RequestBody

Say you have the following JSON:

{
  "rootNode": {
    "firstValue":"",
    "secondValue":""
  }
}

The class to use for this could look something like this:

public class MyValues {
  private String firstValue;
  private String secondValue;
  ...
}

This class will however not map directly to the JSON above via @RequestBody, and this is because the JSON contains a root node (“rootNode”)

The solution here is to wrap the MyValues class into a “root class” like this:

public class MyValuesWrapper {
  MyValues rootNode;
  ...
}

After this you should be able to parse the request body automatically with @ResponseBody like this:

 @PostMapping(value = "/myValues")
  public int postValues(@RequestBody MyValuesWrapper wrappedRequest) {
  
  // Optional: Unwrap for easier access
  MyValues request = wrappedRequest.getMyValues();
  ...

Hope this helps somebody (or me in the future 🙂 )

Tested on Spring Boot v2.3.8 and Java 11

Git: My aliases

Every time you start a new assignment on a new computer all your aliases are gone. I’ll put them here for easy access, and if someone likes them they can use them too 🙂

git config --global alias.co checkout
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.last 'log -1 HEAD'

Tested with Git v 2.24.3 on OSX and Linux