在JavaScript中,toBeEqual()
是一个测试函数,用于比较两个参数是否相等。如果不同的URL在测试中通过了toBeEqual()
,那么很可能是因为它们具有相同的基本值,但具有不同的查询参数或URL锚点。
为了避免这种情况,可以使用URLSearchParams
对象来比较URL query参数,如下所示:
const urlA = new URL('https://example.com/?foo=bar');
const urlB = new URL('https://example.com/?baz=qux');
expect(urlA.pathname).toBe(urlB.pathname); // passes
expect(urlA.searchParams).toEqual(urlB.searchParams); // passes
如果需要比较URL锚点,则可以使用以下代码进行比较:
const urlA = new URL('https://example.com/#foo');
const urlB = new URL('https://example.com/#bar');
expect(urlA.pathname).toBe(urlB.pathname); // passes
expect(urlA.hash).toBe(urlB.hash); // passes
通过使用上述方法,可以确保不同的URL不会通过toBeEqual()
测试。