84348047 |
import addChangeUrlEvent from "./change-url-event";
|
30db14b1 |
it("it should add changeUrlEventCreator to popstate,pushstate,replacestate", () => {
// given
const window = {};
const map = {};
window.addEventListener = jest.fn((event, cb) => {
map[event] = cb;
});
// when
addChangeUrlEvent(window);
// then
|
84348047 |
expect(map["popstate"]).toBeDefined();
expect(map["pushstate"]).toBeDefined();
expect(map["replacestate"]).toBeDefined();
|
30db14b1 |
});
it("given event handler should generate a urlchange event only when url changes", () => {
// given
const window = {
location: {
|
84348047 |
hash: "#hash",
host: "example.com",
hostname: "example",
origin: "",
href: "",
pathname: "/path/to/thing",
|
30db14b1 |
port: 80,
|
84348047 |
protocol: "https:"
|
30db14b1 |
}
};
const map = {};
const calls = [];
window.addEventListener = jest.fn((event, cb) => {
map[event] = cb;
});
window.dispatchEvent = jest.fn(ev => {
const evName = ev.type;
calls.push(ev);
|
84348047 |
if (map[evName]) {
|
30db14b1 |
map[evName].handleEvent(ev);
}
});
// when
addChangeUrlEvent(window);
|
84348047 |
window.dispatchEvent(new Event("popstate"));
window.dispatchEvent(new Event("popstate"));
|
30db14b1 |
// then
expect(calls.length).toEqual(3);
|
84348047 |
expect(calls[1].type).toEqual("urlchanged");
|
30db14b1 |
expect(calls[1].detail).toEqual(window.location);
//when
|
84348047 |
window.location.pathname = "/new/path";
window.dispatchEvent(new Event("popstate"));
|
30db14b1 |
//then
expect(calls.length).toEqual(5);
|
84348047 |
expect(calls[4].type).toEqual("urlchanged");
|
30db14b1 |
expect(calls[4].detail).toEqual(window.location);
});
it("should only add url events 1x when addChangeUrlEvent is called on window more than 1x", () => {
|
09761a45 |
// given
|
0af677b3 |
const window = {};
|
30db14b1 |
const map = {};
window.addEventListener = jest.fn((event, cb) => {
|
84348047 |
if (!map[event]) {
|
30db14b1 |
map[event] = [];
}
map[event].push(cb);
});
// when
addChangeUrlEvent(window);
addChangeUrlEvent(window);
addChangeUrlEvent(window);
expect(Object.keys(map).length).toEqual(3);
//then
for (let event of Object.keys(map)) {
expect(map[event].length).toEqual(1);
}
|
27fb05ae |
});
|