location.href property vs. location.assign() method

后端 未结 5 2028
名媛妹妹
名媛妹妹 2020-12-05 09:17

Is there any particular advantage/disadvantage in JavaScript memory consumption between using location.href = url as opposed to location.assign(url)

5条回答
  •  孤城傲影
    2020-12-05 09:41

    I know this is old, but I stumbled on this when I was looking for a way to check my unit tests were redirecting to the correct url.

    I would go with window.location.assign() if you are more concerned with testing. Using a function allows you to mock said function and check the url input parameters.

    So, using jest:

    window.location.assign = jest.fn();
    
    myUrlUpdateFunction();
    
    expect(window.location.assign).toBeCalledWith('http://my.url');
    
    // Clean up :)
    window.location.assign.mockRestore();
    

提交回复
热议问题