store-exported-later.test.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * A store exported by a LATER statement — `const useStore = create(…)` then
  3. * `export default useStore` — is exported, and its actions are extracted like
  4. * an `export const` store's (object-literal-methods.test.ts covers that
  5. * form). The scope rule that keeps inline-object noise out still holds: a
  6. * store nothing exports stays a constant.
  7. */
  8. import { describe, it, expect, beforeAll } from 'vitest';
  9. import { extractFromSource } from '../src/extraction';
  10. import { initGrammars, loadAllGrammars } from '../src/extraction/grammars';
  11. beforeAll(async () => {
  12. await initGrammars();
  13. await loadAllGrammars();
  14. });
  15. const fnNames = (code: string, file = 'store.ts') =>
  16. extractFromSource(file, code)
  17. .nodes.filter((n) => n.kind === 'function')
  18. .map((n) => n.name);
  19. describe('store actions on a later-exported const', () => {
  20. it('export default NAME', () => {
  21. const code = `
  22. import { create } from 'zustand'
  23. const useCaptureStorage = create<State>((set, get) => ({
  24. object: null,
  25. setSettings: (settings: Settings) => {
  26. set({ settings })
  27. },
  28. reset: () => set({ object: null }),
  29. }))
  30. export default useCaptureStorage
  31. `;
  32. expect(fnNames(code)).toEqual(expect.arrayContaining(['setSettings', 'reset']));
  33. });
  34. it('export { NAME } and export { NAME as default }', () => {
  35. const named = `
  36. const useStore = create((set) => ({ bump: () => set({}) }))
  37. export { useStore }
  38. `;
  39. const asDefault = `
  40. const useStore = create((set) => ({ bump: () => set({}) }))
  41. export { useStore as default }
  42. `;
  43. expect(fnNames(named)).toContain('bump');
  44. expect(fnNames(asDefault)).toContain('bump');
  45. });
  46. it('a const nothing exports keeps its members out of the graph', () => {
  47. const code = `
  48. const useStore = create((set) => ({ bump: () => set({}) }))
  49. export const other = 1
  50. `;
  51. expect(fnNames(code)).not.toContain('bump');
  52. });
  53. it('is not fooled by a different name in the export', () => {
  54. const code = `
  55. const useStoreInternal = create((set) => ({ bump: () => set({}) }))
  56. const useStore = 1
  57. export default useStore
  58. `;
  59. expect(fnNames(code)).not.toContain('bump');
  60. });
  61. });