fullstorydev / fullstory-browser-sdk

Official FullStory SDK for JavaScript, for web browsers
MIT License
55 stars 17 forks source link

`FullStory is not loaded, please ensure the init function is invoked before calling FullStory API functions` even though i have `init` at root #133

Closed brittanyjoiner15 closed 2 years ago

brittanyjoiner15 commented 2 years ago

Hi! I'm having an issue with Jest. App is working fine but tests aren't passing because it says FullStory is not loaded, please ensure the init function is invoked before calling FullStory API functions

I have tried both call FullStory.init at the root index.tsx and also tried it in the root app.tsx, but in either one, I still seem to get the error.

(I found some other similar issues, but they seemed to all reference calling init at the root, which I believe I've done, so I'm a bit stuck!)

brittanyjoiner15 commented 2 years ago

Update on this in case anyone else comes across it. Here's how I was able to solve it

Basically, we had to mock a global import, so the solution was to create a folder at the root of our client (same place we had our jest config file and our app.tsx) that basically gives jest a place to lookup FullStory mocks. So the structure is __mock__/@fullstory/browser and has an index.jsx file that just looks like this:


// FullStory mock functions for jest
export const init = () => {};
export const setUserVars = () => {};
export const setEvent = () => {};
export const setVars = () => {};

I exported a const for each fullstory function i called and just set it to a blank function and that fixed the errors I was seeing in the tests!

patrick-fs commented 2 years ago

Hi @brittanyjoiner15 thanks for raising this issue and leaving behind a solution that worked!

All of the browser SDK functions are wrapped in a guard that verifies whether the window global variable has the FullStory namespace defined on it: https://github.com/fullstorydev/fullstory-browser-sdk/blob/31bbdb9dc52f31a566409f178d7bd08c361c1f4e/src/index.js#L3

Jest doesn't provide a window global object so it will need to be mocked. In addition to your solution, I think you might be able to mock window prior to running your tests and and this will allow FullSory.init and subsequent calls to FullStory SDK functions to not error when under test.

Here are a couple of resources I found online that might be helpful:

Thanks again!

brittanyjoiner15 commented 2 years ago

thanks @patrick-fs good to know!