diff --git a/spec/useLoadClientScript.spec.tsx b/spec/useLoadClientScript.spec.tsx index 4f5dbb5..f1bf4be 100644 --- a/spec/useLoadClientScript.spec.tsx +++ b/spec/useLoadClientScript.spec.tsx @@ -70,20 +70,22 @@ describe("useLoadClientScript", () => { }) it("remove existing Shopify markets related scripts before loading new ones", () => { - const existingScript = document.createElement("script") - existingScript.setAttribute("nosto-client-script", "") - document.body.appendChild(existingScript) + const props = { account: testAccount, shopifyMarkets: { marketId: "123", language: "en" } } + const hook = renderHook(props => useLoadClientScript(props), { initialProps: props }) + expect(getScriptSources()).toEqual([ + `http://connect.nosto.com/script/shopify/market/nosto.js?merchant=${testAccount}&market=123&locale=en` + ]) - const nostoSandbox = document.createElement("div") - nostoSandbox.id = "nosto-sandbox" - document.body.appendChild(nostoSandbox) + const existingScript = document.querySelector("[nosto-client-script]") + const nostoSandbox = document.querySelector("#nosto-sandbox") - renderHook(() => useLoadClientScript({ account: testAccount, shopifyMarkets: { marketId: "123", language: "en" } })) + Object.assign(props.shopifyMarkets, { marketId: "234", language: "fr" }) + hook.rerender(props) expect(document.body.contains(existingScript)).toBe(false) expect(document.body.contains(nostoSandbox)).toBe(false) expect(getScriptSources()).toEqual([ - `http://connect.nosto.com/script/shopify/market/nosto.js?merchant=${testAccount}&market=123&locale=en` + `http://connect.nosto.com/script/shopify/market/nosto.js?merchant=${testAccount}&market=234&locale=fr` ]) }) }) \ No newline at end of file diff --git a/src/hooks/useLoadClientScript.ts b/src/hooks/useLoadClientScript.ts index 4d1ef94..1d6359f 100644 --- a/src/hooks/useLoadClientScript.ts +++ b/src/hooks/useLoadClientScript.ts @@ -57,11 +57,11 @@ export function useLoadClientScript(props: NostoScriptProps) { const marketId = String(shopifyMarkets?.marketId || "") const language = shopifyMarkets?.language || "" - const existingScriptAttributes = + const attributeMismatch = existingScript?.getAttribute("nosto-language") !== language || existingScript?.getAttribute("nosto-market-id") !== marketId - if (!existingScript || existingScriptAttributes) { + if (!existingScript || attributeMismatch) { if (clientScriptLoaded) { setClientScriptLoaded(false) } @@ -80,7 +80,7 @@ export function useLoadClientScript(props: NostoScriptProps) { document.body.appendChild(script) } } - }, [shopifyMarkets]) + }, [shopifyMarkets?.marketId, shopifyMarkets?.language]) return { clientScriptLoaded } } \ No newline at end of file