Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Draft] feat: partial switch to use client script proxy #175

Merged
merged 7 commits into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 7 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,18 @@
"prettier": "prettier '{src,spec}/**' --list-different",
"prettier:fix": "prettier '{src,spec}/**' --write",
"test": "vitest run --silent",
"test-loud": "vitest run",
"typedoc": "typedoc src/index.ts"
},
"files": [
"dist",
"src"
],
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
"@nosto/nosto-js": "*"
},
"devDependencies": {
"@testing-library/jest-dom": "^6.4.8",
"@testing-library/react": "^16.0.0",
Expand All @@ -43,8 +49,6 @@
"eslint-plugin-promise": "^7.1.0",
"eslint-plugin-react": "^7.33.2",
"prettier": "^3.3.3",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router": "^6.25.1",
"react-router-dom": "^6.25.1",
"rimraf": "^6.0.1",
Expand All @@ -61,8 +65,7 @@
".": {
"import": "./dist/index.es.js",
"require": "./dist/index.umd.js"
},
"./shopify-hydrogen": "./dist/index.es.js"
}
},
"bugs": {
"url": "https://github.com/Nosto/nosto-react/issues"
Expand Down
3 changes: 2 additions & 1 deletion spec/category.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import { NostoProvider, NostoCategory, NostoPlacement } from "../src/index"
import RecommendationComponent from "./renderer"
import { waitForRecommendations } from "./utils"
import mockApi from "./mocks/mock-api"
import { mockNostojs } from "@nosto/nosto-js/testing"

test("Category page render", async () => {
const placements = ["categorypage-nosto-1", "categorypage-nosto-2"]
const mocked = mockApi(placements)
window.nostojs = cb => cb(mocked)
mockNostojs(mocked)

render(
<NostoProvider account="dummy-account" recommendationComponent={<RecommendationComponent />} loadScript={false}>
Expand Down
3 changes: 2 additions & 1 deletion spec/checkout.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import { NostoProvider, NostoCheckout, NostoPlacement } from "../src/index"
import RecommendationComponent from "./renderer"
import { waitForRecommendations } from "./utils"
import mockApi from "./mocks/mock-api"
import { mockNostojs } from "@nosto/nosto-js/testing"

test("Checkout page render", async () => {
const placements = ["cartpage-nosto-1", "cartpage-nosto-2", "cartpage-nosto-3"]
const mocked = mockApi(placements)
window.nostojs = cb => cb(mocked)
mockNostojs(mocked)

render(
<NostoProvider
Expand Down
3 changes: 0 additions & 3 deletions spec/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@ interface Event {

function createEvent(event: Event): Event {
return {
cart_popup: false,
preview: false,
skipcache: false,
elements: [],
events: [],
response_mode: "JSON_ORIGINAL",
Expand Down
3 changes: 2 additions & 1 deletion spec/fohofo.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import { NostoProvider, Nosto404, NostoPlacement } from "../src/index"
import RecommendationComponent from "./renderer"
import { waitForRecommendations } from "./utils"
import mockApi from "./mocks/mock-api"
import { mockNostojs } from "@nosto/nosto-js/testing"

test("404 page render", async () => {
const placements = ["notfound-nosto-1", "notfound-nosto-2"]
const mocked = mockApi(placements)
window.nostojs = cb => cb(mocked)
mockNostojs(mocked)

render(
<NostoProvider account="dummy-account" recommendationComponent={<RecommendationComponent />} loadScript={false}>
Expand Down
5 changes: 3 additions & 2 deletions spec/home.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { test, expect, vi } from "vitest"
import { test, expect } from "vitest"
import { render, screen } from "@testing-library/react"
import { NostoProvider, NostoHome, NostoPlacement } from "../src/index"
import RecommendationComponent from "./renderer"
import { waitForRecommendations } from "./utils"
import mockApi from "./mocks/mock-api"
import { mockNostojs } from "@nosto/nosto-js/testing"

test("Home page render", async () => {
const placements = ["frontpage-nosto-1", "frontpage-nosto-2"]
const mocked = mockApi(placements)
window.nostojs = cb => cb(mocked)
mockNostojs(mocked)

render(
<NostoProvider account="dummy-account" recommendationComponent={<RecommendationComponent />} loadScript={false}>
Expand Down
15 changes: 8 additions & 7 deletions spec/mocks/mock-api.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { vi } from "vitest"
import { jsonMockData } from "./mock-data"
import { Product } from "../../src"
import { Action, Data, NostoClient, PageType, Session } from "../../src/types"
import { API, Session, Action, PageType, TaggingData } from "@nosto/nosto-js/client"

function normalizeProduct(data: Product | string) {
return typeof data === "string" ? { product_id: data } : data
}

let latestActionData: Partial<Data>
let latestActionData: Partial<TaggingData>

function newSession(placements: string[]) {
const data: Partial<Data> & { responseMode?: string} = {}
const data: Partial<TaggingData> & { responseMode?: string} = {}

function newAction(pageType: PageType, overrides?: Partial<Data>) {
function newAction(pageType: PageType, overrides?: Partial<TaggingData>) {
const actionData = { ...data, ...overrides, pageType }
latestActionData = actionData

Expand Down Expand Up @@ -53,14 +53,15 @@ function newSession(placements: string[]) {
export default function (placements: string[]) {
const session = newSession(placements)

// TODO: Fix mock
return {
setAutoLoad: vi.fn(),
listen: vi.fn(),
placements: {
injectCampaigns: vi.fn(),
getPlacements: () => placements
},
getPlacements: () => placements,
} as unknown as API["placements"],
defaultSession: () => session,
getData: () => latestActionData,
} satisfies NostoClient & { getData: () => Partial<Data> }
}
}
3 changes: 2 additions & 1 deletion spec/other.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import { NostoProvider, NostoOther, NostoPlacement } from "../src/index"
import RecommendationComponent from "./renderer"
import { waitForRecommendations } from "./utils"
import mockApi from "./mocks/mock-api"
import { mockNostojs } from "@nosto/nosto-js/testing"

test("Other page render", async () => {
const placements = ["cartpage-nosto-1", "categorypage-nosto-1", "productpage-nosto-1", "productpage-nosto-2"]
const mocked = mockApi(placements)
window.nostojs = cb => cb(mocked)
mockNostojs(mocked)

render(
<NostoProvider account="dummy-account" recommendationComponent={<RecommendationComponent />} loadScript={false}>
Expand Down
3 changes: 2 additions & 1 deletion spec/product.sku.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { NostoProvider, NostoPlacement, NostoProduct } from "../src/index"
import RecommendationComponent from "./renderer"
import { waitForRecommendations } from "./utils"
import mockApi from "./mocks/mock-api"
import { mockNostojs } from "@nosto/nosto-js/testing"

function ProductPage() {
const productId = "dummy-product-id"
Expand Down Expand Up @@ -45,7 +46,7 @@ function ProductPage() {
test("Product page with SKU id", async () => {
const placements = ["productpage-nosto-1"]
const mocked = mockApi(placements)
window.nostojs = cb => cb(mocked)
mockNostojs(mocked)

render(
<NostoProvider account="dummy-account" recommendationComponent={<RecommendationComponent />} loadScript={false}>
Expand Down
5 changes: 3 additions & 2 deletions spec/product.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import { NostoProvider, NostoPlacement, NostoProduct, useNostoProduct } from "..
import RecommendationComponent from "./renderer"
import { waitForRecommendations } from "./utils"
import mockApi from "./mocks/mock-api"
import { mockNostojs } from "@nosto/nosto-js/testing"

test("Product page render", async () => {
const placements = ["productpage-nosto-1", "productpage-nosto-2"]
const mocked = mockApi(placements)
window.nostojs = cb => cb(mocked)
mockNostojs(mocked)

render(
<NostoProvider account="dummy-account" recommendationComponent={<RecommendationComponent />} loadScript={false}>
Expand Down Expand Up @@ -46,7 +47,7 @@ test("useNostoProduct validation", async () => {
test("Product Page with ref", async () => {
const placements = ["productpage-nosto-1", "productpage-nosto-2"]
const mocked = mockApi(placements)
window.nostojs = cb => cb(mocked)
mockNostojs(mocked)

render(
<NostoProvider account="dummy-account" recommendationComponent={<RecommendationComponent />} loadScript={false}>
Expand Down
3 changes: 2 additions & 1 deletion spec/search.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import { NostoProvider, NostoSearch, NostoPlacement } from "../src/index"
import RecommendationComponent from "./renderer"
import { waitForRecommendations } from "./utils"
import mockApi from "./mocks/mock-api"
import { mockNostojs } from "@nosto/nosto-js/testing"

test("Search page render", async () => {
const placements = ["searchpage-nosto-1", "searchpage-nosto-2"]
const mocked = mockApi(placements)
window.nostojs = cb => cb(mocked)
mockNostojs(mocked)

render(
<NostoProvider account="dummy-account" recommendationComponent={<RecommendationComponent />} loadScript={false}>
Expand Down
3 changes: 2 additions & 1 deletion spec/session.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import { NostoHome, NostoPlacement, NostoProvider, NostoSession } from "../src/i
import RecommendationComponent from "./renderer"
import { waitForRecommendations } from "./utils"
import mockApi from "./mocks/mock-api"
import { mockNostojs } from "@nosto/nosto-js/testing"

test("Session render", async () => {
const placements = ["frontpage-nosto-1", "frontpage-nosto-3", "frontpage-nosto-4"]
const mocked = mockApi(placements)
window.nostojs = cb => cb(mocked)
mockNostojs(mocked)

const customer = {
firstName: "John",
Expand Down
8 changes: 2 additions & 6 deletions spec/setup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { JSDOM } from "jsdom"
import { afterEach } from "vitest"
import { clearNostoGlobals } from "@nosto/nosto-js/testing"

const { window } = new JSDOM("<html></html>", {
url: "http://localhost",
Expand All @@ -16,12 +17,7 @@ global.navigator = window.navigator
global.window.nostoReactTest = true

afterEach(() => {
// clearing Nosto iframe window handle
window.nosto = undefined
// clearing nostojs stub
window.nostojs = undefined
// clearing Shopify specific Nosto namespace
window.Nosto = undefined
clearNostoGlobals()
document.head.innerHTML = ""
document.body.innerHTML = ""
})
20 changes: 11 additions & 9 deletions spec/useLoadClientScript.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { renderHook } from "@testing-library/react"
import { useLoadClientScript } from "../src/hooks/useLoadClientScript"
import scriptLoader from "../src/hooks/scriptLoader"
import "@testing-library/jest-dom/vitest"
import { nostojs, getNostoWindow, isNostoLoaded } from "@nosto/nosto-js"
import { reloadNosto } from "@nosto/nosto-js/testing"

function loadClientScript(merchant: string) {
const script = document.createElement("script")
Expand All @@ -12,7 +14,7 @@ function loadClientScript(merchant: string) {
script.async = true
const promise = new Promise<void>(resolve => {
script.onload = () => {
window.nosto?.reload({ site: "localhost" })
reloadNosto({ site: "localhost" })
resolve()
}
})
Expand All @@ -29,21 +31,21 @@ describe("useLoadClientScript", () => {

it("loads client script", async () => {
const hook = renderHook(() => useLoadClientScript({ account: testAccount }))
await new Promise(window.nostojs)
await new Promise(nostojs)

hook.rerender()
expect(hook.result.current.clientScriptLoaded).toBe(true)
expect(window.nosto).toBeDefined()
expect(getScriptSources()).toEqual([`http://connect.nosto.com/include/${testAccount}`])
expect(isNostoLoaded()).toBeTruthy()
expect(getScriptSources()).toEqual([`https://connect.nosto.com/include/${testAccount}`])
})

it("support custom script loaders", async () => {
const customScriptLoader = vi.fn(scriptLoader)
const hook = renderHook(() => useLoadClientScript({ account: testAccount, scriptLoader: customScriptLoader }))
await new Promise(window.nostojs)
await new Promise(nostojs)

hook.rerender()
expect(customScriptLoader).toHaveBeenLastCalledWith(`//connect.nosto.com/include/${testAccount}`, {
expect(customScriptLoader).toHaveBeenLastCalledWith(`https://connect.nosto.com/include/${testAccount}`, {
attributes: { "nosto-client-script": "" }
})
})
Expand All @@ -53,7 +55,7 @@ describe("useLoadClientScript", () => {
expect(hook.result.current.clientScriptLoaded).toBe(false)

await loadClientScript(testAccount)
expect(window.nosto).toBeDefined()
expect(isNostoLoaded()).toBeTruthy()

hook.rerender()
expect(hook.result.current.clientScriptLoaded).toBe(true)
Expand All @@ -62,7 +64,7 @@ describe("useLoadClientScript", () => {

it("set loaded state to true when client is loaded externally before", async () => {
await loadClientScript(testAccount)
expect(window.nosto).toBeDefined()
expect(isNostoLoaded()).toBeTruthy()

const { result } = renderHook(() => useLoadClientScript({ loadScript: false, account: testAccount }))
expect(result.current.clientScriptLoaded).toBe(true)
Expand All @@ -71,7 +73,7 @@ describe("useLoadClientScript", () => {

it("reloads client script once with loadScript=false", async () => {
await loadClientScript(testAccount)
const reloadSpy = vi.spyOn(window.nosto!, "reload")
const reloadSpy = vi.spyOn(getNostoWindow()!, "reload")

const hook = renderHook(() => useLoadClientScript({ loadScript: false, account: testAccount }))
expect(reloadSpy).toHaveBeenCalledTimes(1)
Expand Down
Loading
Loading