In my code snippet, I have a function that constructs a complete URL for redirection:
import { redirect } from './some-utils'
export const goToURL = () => {
const url = window.location.origin + window.location.pathname
redirect(url)
}
Now, I am attempting to create a TypeScript test to verify the correctness of the URL string:
describe('my-test-file', () => {
let originalWindowLocation
const redirect = jest.fn()
beforeEach(() => {
jest.resetAllMocks()
originalWindowLocation = window.location
})
afterEach(() => {
window.location = originalWindowLocation
})
it('should validate the redirected URL', () => {
delete window.location // cannot proceed due to TS error
window.location = { origin: 'https://www.example.com', pathname: '/mypath' } // facing TS complaint
goToURL()
expect(redirect).toHaveBeenCalledTimes(1)
expect(redirect).toHaveBeeenCalledWith('https://www.example.com/mypath')
})
})
However, encountering two TypeScript errors. Firstly, on the delete
line:
The operand of a 'delete' operator must be optional.
And secondly, during the assignment of window.location
:
Type '{ origin: string; pathname: string; }' is not assignable to type 'Location | (string & Location)'. Type '{ origin: string; pathname: string; }' is not assignable to type 'string & Location'. Type '{ origin: string; pathname: string; }' is not assignable to type 'string'.
My attempts at rectifying these issues by altering the code did remove the TS errors, but the test no longer passes as expected. It seems to utilize the domain of my application rather than the specified one in the test.
Would appreciate any assistance in resolving the TypeScript errors while ensuring successful test execution.
Edit:
Even trying
window.location = 'https://www.example.com/mypath'
does not resolve the issue and results in a TS error:
Type 'string' is not assignable to type 'Location | (string & Location)'
Using
window.location.href = 'https://www.example.com/mypath'
resolves the TS errors, but the test outcome remains unchanged.
Similarly, with
window.location.assign(https://www.example.com/mypath')
, the TS errors disappear but the test result stays the same.