level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
2,248
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__/__snapshots__/config.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`loadSiteConfig website with .cjs siteConfig 1`] = ` { "siteConfig": { "baseUrl": "/", "baseUrlIssueBanner": true, "clientModules": [], "customFields": {}, "headTags": [], "i18n": { "defaultLocale": "en", "localeConfigs": {}, "locales": [ "en", ], "path": "i18n", }, "markdown": { "format": "mdx", "mdx1Compat": { "admonitions": true, "comments": true, "headingIds": true, }, "mermaid": false, "preprocessor": undefined, }, "noIndex": false, "onBrokenLinks": "throw", "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "plugins": [], "presets": [], "scripts": [], "staticDirectories": [ "static", ], "stylesheets": [], "tagline": "", "themeConfig": {}, "themes": [], "title": "title", "titleDelimiter": "|", "url": "https://example.com", }, "siteConfigPath": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/config/docusaurus.config.cjs", } `; exports[`loadSiteConfig website with ts + js config 1`] = ` { "siteConfig": { "baseUrl": "/", "baseUrlIssueBanner": true, "clientModules": [], "customFields": {}, "headTags": [], "i18n": { "defaultLocale": "en", "localeConfigs": {}, "locales": [ "en", ], "path": "i18n", }, "markdown": { "format": "mdx", "mdx1Compat": { "admonitions": true, "comments": true, "headingIds": true, }, "mermaid": false, "preprocessor": undefined, }, "noIndex": false, "onBrokenLinks": "throw", "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "plugins": [], "presets": [], "scripts": [], "staticDirectories": [ "static", ], "stylesheets": [], "tagline": "", "themeConfig": {}, "themes": [], "title": "TS title", "titleDelimiter": "|", "url": "https://example.com", }, "siteConfigPath": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/config/sites/ts-and-js-site/docusaurus.config.ts", } `; exports[`loadSiteConfig website with valid JS CJS config 1`] = ` { "siteConfig": { "baseUrl": "/", "baseUrlIssueBanner": true, "clientModules": [], "customFields": {}, "headTags": [], "i18n": { "defaultLocale": "en", "localeConfigs": {}, "locales": [ "en", ], "path": "i18n", }, "markdown": { "format": "mdx", "mdx1Compat": { "admonitions": true, "comments": true, "headingIds": true, }, "mermaid": false, "preprocessor": undefined, }, "noIndex": false, "onBrokenLinks": "throw", "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "plugins": [], "presets": [], "scripts": [], "staticDirectories": [ "static", ], "stylesheets": [], "tagline": "", "themeConfig": {}, "themes": [], "title": "title", "titleDelimiter": "|", "url": "https://example.com", }, "siteConfigPath": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/config/configCJS.js", } `; exports[`loadSiteConfig website with valid JS ESM config 1`] = ` { "siteConfig": { "baseUrl": "/", "baseUrlIssueBanner": true, "clientModules": [], "customFields": {}, "headTags": [], "i18n": { "defaultLocale": "en", "localeConfigs": {}, "locales": [ "en", ], "path": "i18n", }, "markdown": { "format": "mdx", "mdx1Compat": { "admonitions": true, "comments": true, "headingIds": true, }, "mermaid": false, "preprocessor": undefined, }, "noIndex": false, "onBrokenLinks": "throw", "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "plugins": [], "presets": [], "scripts": [], "staticDirectories": [ "static", ], "stylesheets": [], "tagline": "", "themeConfig": {}, "themes": [], "title": "title", "titleDelimiter": "|", "url": "https://example.com", }, "siteConfigPath": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/config/configESM.js", } `; exports[`loadSiteConfig website with valid TypeScript CJS config 1`] = ` { "siteConfig": { "baseUrl": "/", "baseUrlIssueBanner": true, "clientModules": [], "customFields": {}, "headTags": [], "i18n": { "defaultLocale": "en", "localeConfigs": {}, "locales": [ "en", ], "path": "i18n", }, "markdown": { "format": "mdx", "mdx1Compat": { "admonitions": true, "comments": true, "headingIds": true, }, "mermaid": false, "preprocessor": undefined, }, "noIndex": false, "onBrokenLinks": "throw", "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "plugins": [], "presets": [], "scripts": [], "staticDirectories": [ "static", ], "stylesheets": [], "tagline": "", "themeConfig": {}, "themes": [], "title": "title", "titleDelimiter": "|", "url": "https://example.com", }, "siteConfigPath": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/config/configCJS.ts", } `; exports[`loadSiteConfig website with valid TypeScript ESM config 1`] = ` { "siteConfig": { "baseUrl": "/", "baseUrlIssueBanner": true, "clientModules": [], "customFields": {}, "headTags": [], "i18n": { "defaultLocale": "en", "localeConfigs": {}, "locales": [ "en", ], "path": "i18n", }, "markdown": { "format": "mdx", "mdx1Compat": { "admonitions": true, "comments": true, "headingIds": true, }, "mermaid": false, "preprocessor": undefined, }, "noIndex": false, "onBrokenLinks": "throw", "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "plugins": [], "presets": [], "scripts": [], "staticDirectories": [ "static", ], "stylesheets": [], "tagline": "", "themeConfig": {}, "themes": [], "title": "title", "titleDelimiter": "|", "url": "https://example.com", }, "siteConfigPath": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/config/configESM.ts", } `; exports[`loadSiteConfig website with valid async config 1`] = ` { "siteConfig": { "baseUrl": "/", "baseUrlIssueBanner": true, "clientModules": [], "customFields": {}, "headTags": [], "i18n": { "defaultLocale": "en", "localeConfigs": {}, "locales": [ "en", ], "path": "i18n", }, "markdown": { "format": "mdx", "mdx1Compat": { "admonitions": true, "comments": true, "headingIds": true, }, "mermaid": false, "preprocessor": undefined, }, "noIndex": false, "onBrokenLinks": "throw", "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "organizationName": "endiliey", "plugins": [], "presets": [], "projectName": "hello", "scripts": [], "staticDirectories": [ "static", ], "stylesheets": [], "tagline": "Hello World", "themeConfig": {}, "themes": [], "title": "Hello", "titleDelimiter": "|", "url": "https://docusaurus.io", }, "siteConfigPath": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/config/configAsync.config.js", } `; exports[`loadSiteConfig website with valid async config creator function 1`] = ` { "siteConfig": { "baseUrl": "/", "baseUrlIssueBanner": true, "clientModules": [], "customFields": {}, "headTags": [], "i18n": { "defaultLocale": "en", "localeConfigs": {}, "locales": [ "en", ], "path": "i18n", }, "markdown": { "format": "mdx", "mdx1Compat": { "admonitions": true, "comments": true, "headingIds": true, }, "mermaid": false, "preprocessor": undefined, }, "noIndex": false, "onBrokenLinks": "throw", "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "organizationName": "endiliey", "plugins": [], "presets": [], "projectName": "hello", "scripts": [], "staticDirectories": [ "static", ], "stylesheets": [], "tagline": "Hello World", "themeConfig": {}, "themes": [], "title": "Hello", "titleDelimiter": "|", "url": "https://docusaurus.io", }, "siteConfigPath": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/config/createConfigAsync.config.js", } `; exports[`loadSiteConfig website with valid config creator function 1`] = ` { "siteConfig": { "baseUrl": "/", "baseUrlIssueBanner": true, "clientModules": [], "customFields": {}, "headTags": [], "i18n": { "defaultLocale": "en", "localeConfigs": {}, "locales": [ "en", ], "path": "i18n", }, "markdown": { "format": "mdx", "mdx1Compat": { "admonitions": true, "comments": true, "headingIds": true, }, "mermaid": false, "preprocessor": undefined, }, "noIndex": false, "onBrokenLinks": "throw", "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "organizationName": "endiliey", "plugins": [], "presets": [], "projectName": "hello", "scripts": [], "staticDirectories": [ "static", ], "stylesheets": [], "tagline": "Hello World", "themeConfig": {}, "themes": [], "title": "Hello", "titleDelimiter": "|", "url": "https://docusaurus.io", }, "siteConfigPath": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/config/createConfig.config.js", } `; exports[`loadSiteConfig website with valid siteConfig 1`] = ` { "siteConfig": { "baseUrl": "/", "baseUrlIssueBanner": true, "clientModules": [ "foo.js", ], "customFields": {}, "favicon": "img/docusaurus.ico", "headTags": [], "i18n": { "defaultLocale": "en", "localeConfigs": {}, "locales": [ "en", ], "path": "i18n", }, "markdown": { "format": "mdx", "mdx1Compat": { "admonitions": true, "comments": true, "headingIds": true, }, "mermaid": false, "preprocessor": undefined, }, "noIndex": false, "onBrokenLinks": "throw", "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "organizationName": "endiliey", "plugins": [ [ "@docusaurus/plugin-content-docs", { "path": "../docs", }, ], "@docusaurus/plugin-content-pages", ], "presets": [], "projectName": "hello", "scripts": [], "staticDirectories": [ "static", ], "stylesheets": [], "tagline": "Hello World", "themeConfig": {}, "themes": [], "title": "Hello", "titleDelimiter": "|", "url": "https://docusaurus.io", }, "siteConfigPath": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/simple-site/docusaurus.config.js", } `;
2,249
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__/__snapshots__/configValidation.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`normalizeConfig should throw error if plugins is not a string and it's not an array #1 for the input of: [123] 1`] = ` " => Bad Docusaurus plugin value plugins[0]. Example valid plugin config: { plugins: [ ["@docusaurus/plugin-content-docs",options], "./myPlugin", ["./myPlugin",{someOption: 42}], function myPlugin() { }, [function myPlugin() { },options] ], }; " `; exports[`normalizeConfig should throw error if plugins is not an array of [string, object][] #1 for the input of: [[Array]] 1`] = ` " => Bad Docusaurus plugin value plugins[0]. Example valid plugin config: { plugins: [ ["@docusaurus/plugin-content-docs",options], "./myPlugin", ["./myPlugin",{someOption: 42}], function myPlugin() { }, [function myPlugin() { },options] ], }; " `; exports[`normalizeConfig should throw error if plugins is not an array of [string, object][] #2 for the input of: [[Array]] 1`] = ` " => Bad Docusaurus plugin value plugins[0]. Example valid plugin config: { plugins: [ ["@docusaurus/plugin-content-docs",options], "./myPlugin", ["./myPlugin",{someOption: 42}], function myPlugin() { }, [function myPlugin() { },options] ], }; " `; exports[`normalizeConfig should throw error if plugins is not an array of [string, object][] #3 for the input of: [[Array]] 1`] = ` " => Bad Docusaurus plugin value plugins[0]. Example valid plugin config: { plugins: [ ["@docusaurus/plugin-content-docs",options], "./myPlugin", ["./myPlugin",{someOption: 42}], function myPlugin() { }, [function myPlugin() { },options] ], }; " `; exports[`normalizeConfig should throw error if plugins is not array for the input of: {} 1`] = ` ""plugins" must be an array " `; exports[`normalizeConfig should throw error if themes is not a string and it's not an array #1 for the input of: [123] 1`] = ` " => Bad Docusaurus theme value themes[0]. Example valid theme config: { themes: [ ["@docusaurus/theme-classic",options], "./myTheme", ["./myTheme",{someOption: 42}], function myTheme() { }, [function myTheme() { },options] ], }; " `; exports[`normalizeConfig should throw error if themes is not an array of [string, object][] #1 for the input of: [[Array]] 1`] = ` " => Bad Docusaurus theme value themes[0]. Example valid theme config: { themes: [ ["@docusaurus/theme-classic",options], "./myTheme", ["./myTheme",{someOption: 42}], function myTheme() { }, [function myTheme() { },options] ], }; " `; exports[`normalizeConfig should throw error if themes is not an array of [string, object][] #2 for the input of: [[Array]] 1`] = ` " => Bad Docusaurus theme value themes[0]. Example valid theme config: { themes: [ ["@docusaurus/theme-classic",options], "./myTheme", ["./myTheme",{someOption: 42}], function myTheme() { }, [function myTheme() { },options] ], }; " `; exports[`normalizeConfig should throw error if themes is not an array of [string, object][] #3 for the input of: [[Array]] 1`] = ` " => Bad Docusaurus theme value themes[0]. Example valid theme config: { themes: [ ["@docusaurus/theme-classic",options], "./myTheme", ["./myTheme",{someOption: 42}], function myTheme() { }, [function myTheme() { },options] ], }; " `; exports[`normalizeConfig should throw error if themes is not array for the input of: {} 1`] = ` ""themes" must be an array " `; exports[`normalizeConfig throws error for required fields 1`] = ` ""baseUrl" is required "title" is required "url" is required "themes" must be an array "presets" must be an array "scripts" must be an array "stylesheets" must be an array These field(s) ("invalidField",) are not recognized in docusaurus.config.js. If you still want these fields to be in your configuration, put them in the "customFields" field. See https://docusaurus.io/docs/api/docusaurus-config/#customfields" `; exports[`normalizeConfig throws error for unknown field 1`] = ` "These field(s) ("invalid",) are not recognized in docusaurus.config.js. If you still want these fields to be in your configuration, put them in the "customFields" field. See https://docusaurus.io/docs/api/docusaurus-config/#customfields" `; exports[`normalizeConfig throws for "error" reporting severity 1`] = ` ""onBrokenLinks" must be one of [ignore, log, warn, throw] " `;
2,250
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`load loads props for site with custom i18n path 1`] = ` { "baseUrl": "/", "codeTranslations": {}, "generatedFilesDir": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/custom-i18n-site/.docusaurus", "headTags": "", "i18n": { "currentLocale": "en", "defaultLocale": "en", "localeConfigs": { "en": { "calendar": "gregory", "direction": "ltr", "htmlLang": "en", "label": "English", "path": "en-custom", }, "zh-Hans": { "calendar": "gregory", "direction": "ltr", "htmlLang": "zh-Hans", "label": "简体中文", "path": "zh-Hans-custom", }, }, "locales": [ "en", "zh-Hans", ], "path": "i18n", }, "localizationDir": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/custom-i18n-site/i18n/en-custom", "outDir": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/custom-i18n-site/build", "plugins": [ { "content": undefined, "getClientModules": [Function], "injectHtmlTags": [Function], "name": "docusaurus-bootstrap-plugin", "options": { "id": "default", }, "path": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/custom-i18n-site", "version": { "type": "synthetic", }, }, { "configureWebpack": [Function], "content": undefined, "name": "docusaurus-mdx-fallback-plugin", "options": { "id": "default", }, "path": ".", "version": { "type": "synthetic", }, }, ], "postBodyTags": "", "preBodyTags": "", "routes": [], "routesPaths": [ "/404.html", ], "siteConfig": { "baseUrl": "/", "baseUrlIssueBanner": true, "clientModules": [], "customFields": {}, "headTags": [], "i18n": { "defaultLocale": "en", "localeConfigs": { "en": { "direction": "ltr", "path": "en-custom", }, "zh-Hans": { "direction": "ltr", "path": "zh-Hans-custom", }, }, "locales": [ "en", "zh-Hans", ], "path": "i18n", }, "markdown": { "format": "mdx", "mdx1Compat": { "admonitions": true, "comments": true, "headingIds": true, }, "mermaid": false, "preprocessor": undefined, }, "noIndex": false, "onBrokenLinks": "throw", "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "plugins": [], "presets": [], "scripts": [], "staticDirectories": [ "static", ], "stylesheets": [], "tagline": "", "themeConfig": {}, "themes": [], "title": "Site", "titleDelimiter": "|", "url": "https://example.com", }, "siteConfigPath": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/custom-i18n-site/docusaurus.config.js", "siteDir": "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/custom-i18n-site", "siteMetadata": { "docusaurusVersion": "<CURRENT_VERSION>", "pluginVersions": {}, "siteVersion": undefined, }, } `;
2,251
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__/__snapshots__/routes.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`handleDuplicateRoutes works 1`] = ` "Duplicate routes found! - Attempting to create page at /search, but a page already exists at this route. - Attempting to create page at /sameDoc, but a page already exists at this route. - Attempting to create page at /, but a page already exists at this route. - Attempting to create page at /, but a page already exists at this route. This could lead to non-deterministic routing behavior." `; exports[`loadRoutes loads flat route config 1`] = ` { "registry": { "__comp---theme-blog-list-pagea-6-a-7ba": "@theme/BlogListPage", "content---blog-0-b-4-09e": "blog/2018-12-14-Happy-First-Birthday-Slash.md?truncated=true", "content---blog-7-b-8-fd9": "blog/2018-12-14-Happy-First-Birthday-Slash.md", "metadata---blog-0-b-6-74c": "blog-2018-12-14-happy-first-birthday-slash-d2c.json", }, "routesChunkNames": { "/blog-599": { "__comp": "__comp---theme-blog-list-pagea-6-a-7ba", "items": [ { "content": "content---blog-0-b-4-09e", "metadata": "metadata---blog-0-b-6-74c", }, { "content": "content---blog-7-b-8-fd9", }, { "content": "content---blog-7-b-8-fd9", }, ], }, }, "routesConfig": "import React from 'react'; import ComponentCreator from '@docusaurus/ComponentCreator'; export default [ { path: '/blog', component: ComponentCreator('/blog', '599'), exact: true }, { path: '*', component: ComponentCreator('*'), }, ]; ", "routesPaths": [ "/404.html", "/blog", ], } `; exports[`loadRoutes loads nested route config 1`] = ` { "registry": { "__comp---theme-doc-item-178-a40": "@theme/DocItem", "__comp---theme-doc-roota-94-67a": "@theme/DocRoot", "content---docs-foo-baz-8-ce-61e": "docs/foo/baz.md", "content---docs-helloaff-811": "docs/hello.md", "docsMetadata---docs-routef-34-881": "docs-b5f.json", "metadata---docs-foo-baz-2-cf-fa7": "docs-foo-baz-dd9.json", "metadata---docs-hello-956-741": "docs-hello-da2.json", "plugin---docs-hello-665-3ca": "pluginRouteContextModule-100.json", }, "routesChunkNames": { "/docs/hello-fcc": { "__comp": "__comp---theme-doc-item-178-a40", "__context": { "plugin": "plugin---docs-hello-665-3ca", }, "content": "content---docs-helloaff-811", "metadata": "metadata---docs-hello-956-741", }, "/docs:route-9d0": { "__comp": "__comp---theme-doc-roota-94-67a", "docsMetadata": "docsMetadata---docs-routef-34-881", }, "docs/foo/baz-eb2": { "__comp": "__comp---theme-doc-item-178-a40", "__context": { "plugin": "plugin---docs-hello-665-3ca", }, "content": "content---docs-foo-baz-8-ce-61e", "metadata": "metadata---docs-foo-baz-2-cf-fa7", }, }, "routesConfig": "import React from 'react'; import ComponentCreator from '@docusaurus/ComponentCreator'; export default [ { path: '/docs:route', component: ComponentCreator('/docs:route', '9d0'), routes: [ { path: '/docs/hello', component: ComponentCreator('/docs/hello', 'fcc'), exact: true, sidebar: "main" }, { path: 'docs/foo/baz', component: ComponentCreator('docs/foo/baz', 'eb2'), sidebar: "secondary", "key:a": "containing colon", "key'b": "containing quote", "key\\"c": "containing double quote", "key,d": "containing comma", 字段: "containing unicode" } ] }, { path: '*', component: ComponentCreator('*'), }, ]; ", "routesPaths": [ "/404.html", "/docs/hello", "docs/foo/baz", ], } `; exports[`loadRoutes loads route config with empty (but valid) path string 1`] = ` { "registry": { "__comp---hello-world-jse-0-f-b6c": "hello/world.js", }, "routesChunkNames": { "-b2a": { "__comp": "__comp---hello-world-jse-0-f-b6c", }, }, "routesConfig": "import React from 'react'; import ComponentCreator from '@docusaurus/ComponentCreator'; export default [ { path: '', component: ComponentCreator('', 'b2a') }, { path: '*', component: ComponentCreator('*'), }, ]; ", "routesPaths": [ "/404.html", "", ], } `;
2,260
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import {loadPlugins} from '..'; import type {Plugin, Props} from '@docusaurus/types'; describe('loadPlugins', () => { it('loads plugins', async () => { const siteDir = path.join(__dirname, '__fixtures__/site-with-plugin'); await expect( loadPlugins({ siteDir, generatedFilesDir: path.join(siteDir, '.docusaurus'), outDir: path.join(siteDir, 'build'), siteConfig: { baseUrl: '/', trailingSlash: true, themeConfig: {}, presets: [], plugins: [ () => ({ name: 'test1', prop: 'a', async loadContent() { // Testing that plugin lifecycle is bound to the instance return this.prop; }, async contentLoaded({content, actions}) { actions.addRoute({ path: 'foo', component: 'Comp', modules: {content: 'path'}, context: {content: 'path'}, }); actions.setGlobalData({content, prop: this.prop}); }, } as Plugin & ThisType<{prop: 'a'}>), ], themes: [ () => ({ name: 'test2', configureWebpack() { return {}; }, }), ], }, siteConfigPath: path.join(siteDir, 'docusaurus.config.js'), } as unknown as Props), ).resolves.toMatchSnapshot(); }); });
2,261
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__/init.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import {loadContext, type LoadContextOptions} from '../../index'; import {initPlugins} from '../init'; describe('initPlugins', () => { async function loadSite(options: Omit<LoadContextOptions, 'siteDir'> = {}) { const siteDir = path.join(__dirname, '__fixtures__', 'site-with-plugin'); const context = await loadContext({...options, siteDir}); const plugins = await initPlugins(context); return {siteDir, context, plugins}; } it('parses plugins correctly and loads them in correct order', async () => { const {context, plugins} = await loadSite(); expect(context.siteConfig.plugins).toHaveLength(6); expect(plugins).toHaveLength(10); expect(plugins[0]!.name).toBe('preset-plugin1'); expect(plugins[1]!.name).toBe('preset-plugin2'); expect(plugins[2]!.name).toBe('preset-theme1'); expect(plugins[3]!.name).toBe('preset-theme2'); expect(plugins[4]!.name).toBe('first-plugin'); expect(plugins[5]!.name).toBe('second-plugin'); expect(plugins[6]!.name).toBe('third-plugin'); expect(plugins[7]!.name).toBe('fourth-plugin'); expect(context.siteConfig.themeConfig).toEqual({ a: 1, esmPlugin: { joi: true, }, tsPlugin: { joi: true, }, }); }); it('throws user-friendly error message for plugins with bad values', async () => { await expect(() => loadSite({config: 'badPlugins.docusaurus.config.js'}), ).rejects.toThrowErrorMatchingSnapshot(); }); });
2,262
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__/moduleShorthand.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {getNamePatterns, resolveModuleName} from '../moduleShorthand'; describe('getNamePatterns', () => { it('resolves plain names', () => { expect(getNamePatterns('awesome', 'plugin')).toEqual([ 'awesome', '@docusaurus/plugin-awesome', 'docusaurus-plugin-awesome', ]); expect(getNamePatterns('awesome', 'theme')).toEqual([ 'awesome', '@docusaurus/theme-awesome', 'docusaurus-theme-awesome', ]); }); it('expands bare scopes', () => { expect(getNamePatterns('@joshcena', 'plugin')).toEqual([ '@joshcena/docusaurus-plugin', ]); expect(getNamePatterns('@joshcena', 'theme')).toEqual([ '@joshcena/docusaurus-theme', ]); }); it('expands scoped names', () => { expect(getNamePatterns('@joshcena/awesome', 'plugin')).toEqual([ '@joshcena/awesome', '@joshcena/docusaurus-plugin-awesome', ]); expect(getNamePatterns('@joshcena/awesome', 'theme')).toEqual([ '@joshcena/awesome', '@joshcena/docusaurus-theme-awesome', ]); }); it('expands deep scoped paths', () => { expect(getNamePatterns('@joshcena/awesome/web', 'plugin')).toEqual([ '@joshcena/awesome/web', '@joshcena/docusaurus-plugin-awesome/web', ]); expect(getNamePatterns('@joshcena/awesome/web', 'theme')).toEqual([ '@joshcena/awesome/web', '@joshcena/docusaurus-theme-awesome/web', ]); }); }); describe('resolveModuleName', () => { it('resolves longhand', () => { expect( resolveModuleName('@docusaurus/plugin-content-docs', require, 'plugin'), ).toBeDefined(); }); it('resolves shorthand', () => { expect(resolveModuleName('content-docs', require, 'plugin')).toBeDefined(); }); it('throws good error message for longhand', () => { expect(() => resolveModuleName('@docusaurus/plugin-content-doc', require, 'plugin'), ).toThrowErrorMatchingInlineSnapshot(` "Docusaurus was unable to resolve the "@docusaurus/plugin-content-doc" plugin. Make sure one of the following packages are installed: - @docusaurus/plugin-content-doc - @docusaurus/docusaurus-plugin-plugin-content-doc" `); }); it('throws good error message for shorthand', () => { expect(() => resolveModuleName('content-doc', require, 'plugin')) .toThrowErrorMatchingInlineSnapshot(` "Docusaurus was unable to resolve the "content-doc" plugin. Make sure one of the following packages are installed: - content-doc - @docusaurus/plugin-content-doc - docusaurus-plugin-content-doc" `); }); });
2,263
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__/pluginIds.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {ensureUniquePluginInstanceIds} from '../pluginIds'; import type {InitializedPlugin} from '@docusaurus/types'; function createTestPlugin(name: string, id?: string) { return { name, options: {id: id ?? 'default'}, } as InitializedPlugin; } describe('ensureUniquePluginInstanceIds', () => { it('accept single instance plugins', async () => { ensureUniquePluginInstanceIds([ createTestPlugin('plugin-docs'), createTestPlugin('plugin-blog'), createTestPlugin('plugin-pages'), ]); }); it('accept single instance plugins, all with sameId', async () => { ensureUniquePluginInstanceIds([ createTestPlugin('plugin-docs', 'sameId'), createTestPlugin('plugin-blog', 'sameId'), createTestPlugin('plugin-pages', 'sameId'), ]); }); it('accept multi instance plugins without id', async () => { ensureUniquePluginInstanceIds([ createTestPlugin('plugin-docs', 'ios'), createTestPlugin('plugin-docs', 'android'), createTestPlugin('plugin-pages', 'pages'), ]); }); it('reject multi instance plugins without id', async () => { expect(() => ensureUniquePluginInstanceIds([ createTestPlugin('plugin-docs'), createTestPlugin('plugin-docs'), ]), ).toThrowErrorMatchingSnapshot(); }); it('reject multi instance plugins with same id', async () => { expect(() => ensureUniquePluginInstanceIds([ createTestPlugin('plugin-docs', 'sameId'), createTestPlugin('plugin-docs', 'sameId'), ]), ).toThrowErrorMatchingSnapshot(); }); it('reject multi instance plugins with some without id', async () => { expect(() => ensureUniquePluginInstanceIds([ createTestPlugin('plugin-docs'), createTestPlugin('plugin-docs', 'ios'), createTestPlugin('plugin-docs'), createTestPlugin('plugin-pages'), createTestPlugin('plugin-pages', 'pages2'), ]), ).toThrowErrorMatchingSnapshot(); }); });
2,264
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__/presets.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import {loadPresets} from '../presets'; import type {LoadContext} from '@docusaurus/types'; describe('loadPresets', () => { it('no presets', async () => { const context = { siteConfigPath: __dirname, siteConfig: { presets: [], }, } as unknown as LoadContext; const presets = await loadPresets(context); expect(presets).toMatchInlineSnapshot(` { "plugins": [], "themes": [], } `); }); it('cjs form', async () => { const context = { siteConfigPath: __dirname, siteConfig: { presets: [ path.join(__dirname, '__fixtures__/presets/preset-plugins.cjs.js'), ], }, } as LoadContext; const presets = await loadPresets(context); expect(presets).toMatchSnapshot(); }); it('esm form', async () => { const context = { siteConfigPath: __dirname, siteConfig: { presets: [ path.join(__dirname, '__fixtures__/presets/preset-plugins.esm.js'), ], }, } as LoadContext; const presets = await loadPresets(context); expect(presets).toMatchSnapshot(); }); it('ts form', async () => { const context = { siteConfigPath: __dirname, siteConfig: { presets: [ path.join(__dirname, '__fixtures__/presets/preset-plugins.ts'), ], }, } as LoadContext; const presets = await loadPresets(context); expect(presets).toMatchSnapshot(); }); it('string form composite', async () => { const context = { siteConfigPath: __dirname, siteConfig: { presets: [ path.join(__dirname, '__fixtures__/presets/preset-plugins.cjs.js'), path.join(__dirname, '__fixtures__/presets/preset-themes.js'), ], }, } as LoadContext; const presets = await loadPresets(context); expect(presets).toMatchSnapshot(); }); it('array form', async () => { const context = { siteConfigPath: __dirname, siteConfig: { presets: [ [path.join(__dirname, '__fixtures__/presets/preset-plugins.cjs.js')], ], }, } as unknown as LoadContext; const presets = await loadPresets(context); expect(presets).toMatchSnapshot(); }); it('array form with options', async () => { const context = { siteConfigPath: __dirname, siteConfig: { presets: [ [ path.join(__dirname, '__fixtures__/presets/preset-plugins.cjs.js'), {docs: {path: '../'}}, ], ], }, } as unknown as LoadContext; const presets = await loadPresets(context); expect(presets).toMatchSnapshot(); }); it('array form composite', async () => { const context = { siteConfigPath: __dirname, siteConfig: { presets: [ [ path.join(__dirname, '__fixtures__/presets/preset-plugins.cjs.js'), {docs: {path: '../'}}, ], [ path.join(__dirname, '__fixtures__/presets/preset-themes.js'), {algolia: {trackingID: 'foo'}}, ], ], }, } as unknown as LoadContext; const presets = await loadPresets(context); expect(presets).toMatchSnapshot(); }); it('mixed form', async () => { const context = { siteConfigPath: __dirname, siteConfig: { presets: [ [ path.join(__dirname, '__fixtures__/presets/preset-plugins.cjs.js'), {docs: {path: '../'}}, ], path.join(__dirname, '__fixtures__/presets/preset-themes.js'), ], }, } as LoadContext; const presets = await loadPresets(context); expect(presets).toMatchSnapshot(); }); it('mixed form with themes', async () => { const context = { siteConfigPath: __dirname, siteConfig: { presets: [ [ path.join(__dirname, '__fixtures__/presets/preset-plugins.cjs.js'), {docs: {path: '../'}}, ], false, null, undefined, path.join(__dirname, '__fixtures__/presets/preset-themes.js'), path.join(__dirname, '__fixtures__/presets/preset-mixed.js'), ], }, } as LoadContext; const presets = await loadPresets(context); expect(presets).toMatchSnapshot(); }); });
2,265
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__/routeConfig.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {applyRouteTrailingSlash, sortConfig} from '../routeConfig'; import type {RouteConfig} from '@docusaurus/types'; import type {ApplyTrailingSlashParams} from '@docusaurus/utils-common'; function route(path: string, subRoutes?: string[]): RouteConfig { const result: RouteConfig = {path, component: 'any'}; if (subRoutes) { result.routes = subRoutes.map((subRoute) => route(subRoute)); } return result; } function params( trailingSlash: boolean | undefined, baseUrl: string = '/', ): ApplyTrailingSlashParams { return {trailingSlash, baseUrl}; } describe('applyRouteTrailingSlash', () => { it('apply to empty', () => { expect(applyRouteTrailingSlash(route(''), params(true))).toEqual( route('/'), ); expect(applyRouteTrailingSlash(route(''), params(false))).toEqual( route(''), ); expect(applyRouteTrailingSlash(route(''), params(undefined))).toEqual( route(''), ); }); it('apply to /', () => { expect(applyRouteTrailingSlash(route('/'), params(true))).toEqual( route('/'), ); expect(applyRouteTrailingSlash(route('/'), params(false))).toEqual( route('/'), ); expect(applyRouteTrailingSlash(route('/'), params(undefined))).toEqual( route('/'), ); }); it('apply to /abc', () => { expect(applyRouteTrailingSlash(route('/abc'), params(true))).toEqual( route('/abc/'), ); expect(applyRouteTrailingSlash(route('/abc'), params(false))).toEqual( route('/abc'), ); expect(applyRouteTrailingSlash(route('/abc'), params(undefined))).toEqual( route('/abc'), ); }); it('apply to /abc/', () => { expect(applyRouteTrailingSlash(route('/abc/'), params(true))).toEqual( route('/abc/'), ); expect(applyRouteTrailingSlash(route('/abc/'), params(false))).toEqual( route('/abc'), ); expect(applyRouteTrailingSlash(route('/abc/'), params(undefined))).toEqual( route('/abc/'), ); }); it('apply to /abc?search#anchor', () => { expect( applyRouteTrailingSlash(route('/abc?search#anchor'), params(true)), ).toEqual(route('/abc/?search#anchor')); expect( applyRouteTrailingSlash(route('/abc?search#anchor'), params(false)), ).toEqual(route('/abc?search#anchor')); expect( applyRouteTrailingSlash(route('/abc?search#anchor'), params(undefined)), ).toEqual(route('/abc?search#anchor')); }); it('apply to /abc/?search#anchor', () => { expect( applyRouteTrailingSlash(route('/abc/?search#anchor'), params(true)), ).toEqual(route('/abc/?search#anchor')); expect( applyRouteTrailingSlash(route('/abc/?search#anchor'), params(false)), ).toEqual(route('/abc?search#anchor')); expect( applyRouteTrailingSlash(route('/abc/?search#anchor'), params(undefined)), ).toEqual(route('/abc/?search#anchor')); }); it('not apply to /abc/?search#anchor when baseUrl=/abc/', () => { const baseUrl = '/abc/'; expect( applyRouteTrailingSlash( route('/abc/?search#anchor'), params(true, baseUrl), ), ).toEqual(route('/abc/?search#anchor')); expect( applyRouteTrailingSlash( route('/abc/?search#anchor'), params(false, baseUrl), ), ).toEqual(route('/abc/?search#anchor')); expect( applyRouteTrailingSlash( route('/abc/?search#anchor'), params(undefined, baseUrl), ), ).toEqual(route('/abc/?search#anchor')); }); it('apply to subroutes', () => { expect( applyRouteTrailingSlash( route('/abc', ['/abc/1', '/abc/2']), params(true), ), ).toEqual(route('/abc/', ['/abc/1/', '/abc/2/'])); expect( applyRouteTrailingSlash( route('/abc', ['/abc/1', '/abc/2']), params(false), ), ).toEqual(route('/abc', ['/abc/1', '/abc/2'])); expect( applyRouteTrailingSlash( route('/abc', ['/abc/1', '/abc/2']), params(undefined), ), ).toEqual(route('/abc', ['/abc/1', '/abc/2'])); }); it('apply for complex case', () => { expect( applyRouteTrailingSlash( route('/abc?search#anchor', ['/abc/1?search', '/abc/2#anchor']), params(true), ), ).toEqual( route('/abc/?search#anchor', ['/abc/1/?search', '/abc/2/#anchor']), ); }); it('apply for complex case with baseUrl', () => { const baseUrl = '/abc/'; expect( applyRouteTrailingSlash( route('/abc/?search#anchor', ['/abc/1?search', '/abc/2#anchor']), params(false, baseUrl), ), ).toEqual(route('/abc/?search#anchor', ['/abc/1?search', '/abc/2#anchor'])); }); }); describe('sortConfig', () => { it('sorts route config correctly', () => { const routes: RouteConfig[] = [ { path: '/', component: '', routes: [ {path: '/someDoc', component: ''}, {path: '/someOtherDoc', component: ''}, ], }, { path: '/', component: '', }, { path: '/', component: '', routes: [{path: '/subroute', component: ''}], }, { path: '/docs', component: '', routes: [ {path: '/docs/someDoc', component: ''}, {path: '/docs/someOtherDoc', component: ''}, ], }, { path: '/community', component: '', }, { path: '/some-page', component: '', }, ]; sortConfig(routes); expect(routes).toMatchSnapshot(); }); it('sorts route config recursively', () => { const routes: RouteConfig[] = [ { path: '/docs', component: '', routes: [ { path: '/docs/tags', component: '', exact: true, }, { path: '/docs', component: '', routes: [ { path: '/docs/doc1', component: '', exact: true, }, { path: '/docs/doc2', component: '', exact: true, }, ], }, { path: '/docs/tags/someTag', component: '', exact: true, }, ], }, { path: '/some/page', component: '', exact: true, }, ]; sortConfig(routes); expect(routes).toMatchSnapshot(); }); it('sorts route config given a baseURL', () => { const baseURL = '/latest/'; const routes: RouteConfig[] = [ { path: baseURL, component: '', routes: [ {path: `${baseURL}someDoc`, component: ''}, {path: `${baseURL}someOtherDoc`, component: ''}, ], }, { path: `${baseURL}example`, component: '', }, { path: `${baseURL}docs`, component: '', routes: [ {path: `${baseURL}docs/someDoc`, component: ''}, {path: `${baseURL}docs/someOtherDoc`, component: ''}, ], }, { path: `${baseURL}community`, component: '', }, { path: `${baseURL}some-page`, component: '', }, { path: `${baseURL}`, component: '', }, ]; sortConfig(routes, baseURL); expect(routes).toMatchSnapshot(); }); });
2,280
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`loadPlugins loads plugins 1`] = ` { "globalData": { "test1": { "default": { "content": "a", "prop": "a", }, }, }, "plugins": [ { "content": "a", "contentLoaded": [Function], "loadContent": [Function], "name": "test1", "options": { "id": "default", }, "path": "<PROJECT_ROOT>/packages/docusaurus/src/server/plugins/__tests__/__fixtures__/site-with-plugin", "prop": "a", "version": { "type": "local", }, }, { "configureWebpack": [Function], "content": undefined, "name": "test2", "options": { "id": "default", }, "path": "<PROJECT_ROOT>/packages/docusaurus/src/server/plugins/__tests__/__fixtures__/site-with-plugin", "version": { "type": "local", }, }, { "content": undefined, "getClientModules": [Function], "injectHtmlTags": [Function], "name": "docusaurus-bootstrap-plugin", "options": { "id": "default", }, "path": "<PROJECT_ROOT>/packages/docusaurus/src/server/plugins/__tests__/__fixtures__/site-with-plugin", "version": { "type": "synthetic", }, }, { "configureWebpack": [Function], "content": undefined, "name": "docusaurus-mdx-fallback-plugin", "options": { "id": "default", }, "path": ".", "version": { "type": "synthetic", }, }, ], "pluginsRouteConfigs": [ { "component": "Comp", "context": { "data": { "content": "path", }, "plugin": "<PROJECT_ROOT>/packages/docusaurus/src/server/plugins/__tests__/__fixtures__/site-with-plugin/.docusaurus/test1/default/plugin-route-context-module-100.json", }, "modules": { "content": "path", }, "path": "foo/", }, ], } `;
2,281
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__/__snapshots__/init.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`initPlugins throws user-friendly error message for plugins with bad values 1`] = ` " => Bad Docusaurus plugin value plugins[0]. Example valid plugin config: { plugins: [ ["@docusaurus/plugin-content-docs",options], "./myPlugin", ["./myPlugin",{someOption: 42}], function myPlugin() { }, [function myPlugin() { },options] ], }; => Bad Docusaurus plugin value plugins[1]. Example valid plugin config: { plugins: [ ["@docusaurus/plugin-content-docs",options], "./myPlugin", ["./myPlugin",{someOption: 42}], function myPlugin() { }, [function myPlugin() { },options] ], }; " `;
2,282
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__/__snapshots__/pluginIds.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`ensureUniquePluginInstanceIds reject multi instance plugins with same id 1`] = ` "Plugin "plugin-docs" is used 2 times with ID "sameId". To use the same plugin multiple times on a Docusaurus site, you need to assign a unique ID to each plugin instance." `; exports[`ensureUniquePluginInstanceIds reject multi instance plugins with some without id 1`] = ` "Plugin "plugin-docs" is used 2 times with ID "default". To use the same plugin multiple times on a Docusaurus site, you need to assign a unique ID to each plugin instance. The plugin ID is "default" by default. It's possible that the preset you are using already includes a plugin instance, in which case you either want to disable the plugin in the preset (to use a single instance), or assign another ID to your extra plugin instance (to use multiple instances)." `; exports[`ensureUniquePluginInstanceIds reject multi instance plugins without id 1`] = ` "Plugin "plugin-docs" is used 2 times with ID "default". To use the same plugin multiple times on a Docusaurus site, you need to assign a unique ID to each plugin instance. The plugin ID is "default" by default. It's possible that the preset you are using already includes a plugin instance, in which case you either want to disable the plugin in the preset (to use a single instance), or assign another ID to your extra plugin instance (to use multiple instances)." `;
2,283
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__/__snapshots__/presets.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`loadPresets array form 1`] = ` { "plugins": [ [ "@docusaurus/plugin-content-docs", undefined, ], [ "@docusaurus/plugin-content-blog", undefined, ], ], "themes": [], } `; exports[`loadPresets array form composite 1`] = ` { "plugins": [ [ "@docusaurus/plugin-content-docs", { "path": "../", }, ], [ "@docusaurus/plugin-content-blog", undefined, ], ], "themes": [ [ "@docusaurus/theme-live-codeblock", undefined, ], [ "@docusaurus/theme-algolia", { "trackingID": "foo", }, ], ], } `; exports[`loadPresets array form with options 1`] = ` { "plugins": [ [ "@docusaurus/plugin-content-docs", { "path": "../", }, ], [ "@docusaurus/plugin-content-blog", undefined, ], ], "themes": [], } `; exports[`loadPresets cjs form 1`] = ` { "plugins": [ [ "@docusaurus/plugin-content-docs", undefined, ], [ "@docusaurus/plugin-content-blog", undefined, ], ], "themes": [], } `; exports[`loadPresets esm form 1`] = ` { "plugins": [ [ "@docusaurus/plugin-content-docs", undefined, ], [ "@docusaurus/plugin-content-blog", undefined, ], ], "themes": [], } `; exports[`loadPresets mixed form 1`] = ` { "plugins": [ [ "@docusaurus/plugin-content-docs", { "path": "../", }, ], [ "@docusaurus/plugin-content-blog", undefined, ], ], "themes": [ [ "@docusaurus/theme-live-codeblock", undefined, ], [ "@docusaurus/theme-algolia", undefined, ], ], } `; exports[`loadPresets mixed form with themes 1`] = ` { "plugins": [ [ "@docusaurus/plugin-content-docs", { "path": "../", }, ], [ "@docusaurus/plugin-content-blog", undefined, ], [ "@docusaurus/plugin-test", undefined, ], false, ], "themes": [ [ "@docusaurus/theme-live-codeblock", undefined, ], [ "@docusaurus/theme-algolia", undefined, ], [ "@docusaurus/theme-classic", undefined, ], null, ], } `; exports[`loadPresets string form composite 1`] = ` { "plugins": [ [ "@docusaurus/plugin-content-docs", undefined, ], [ "@docusaurus/plugin-content-blog", undefined, ], ], "themes": [ [ "@docusaurus/theme-live-codeblock", undefined, ], [ "@docusaurus/theme-algolia", undefined, ], ], } `; exports[`loadPresets ts form 1`] = ` { "plugins": [ [ "@docusaurus/plugin-test", undefined, ], false, ], "themes": [ [ "@docusaurus/theme-classic", undefined, ], null, ], } `;
2,284
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/plugins/__tests__/__snapshots__/routeConfig.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`sortConfig sorts route config correctly 1`] = ` [ { "component": "", "path": "/community", }, { "component": "", "path": "/some-page", }, { "component": "", "path": "/docs", "routes": [ { "component": "", "path": "/docs/someDoc", }, { "component": "", "path": "/docs/someOtherDoc", }, ], }, { "component": "", "path": "/", }, { "component": "", "path": "/", "routes": [ { "component": "", "path": "/someDoc", }, { "component": "", "path": "/someOtherDoc", }, ], }, { "component": "", "path": "/", "routes": [ { "component": "", "path": "/subroute", }, ], }, ] `; exports[`sortConfig sorts route config given a baseURL 1`] = ` [ { "component": "", "path": "/latest/community", }, { "component": "", "path": "/latest/example", }, { "component": "", "path": "/latest/some-page", }, { "component": "", "path": "/latest/docs", "routes": [ { "component": "", "path": "/latest/docs/someDoc", }, { "component": "", "path": "/latest/docs/someOtherDoc", }, ], }, { "component": "", "path": "/latest/", }, { "component": "", "path": "/latest/", "routes": [ { "component": "", "path": "/latest/someDoc", }, { "component": "", "path": "/latest/someOtherDoc", }, ], }, ] `; exports[`sortConfig sorts route config recursively 1`] = ` [ { "component": "", "exact": true, "path": "/some/page", }, { "component": "", "path": "/docs", "routes": [ { "component": "", "exact": true, "path": "/docs/tags", }, { "component": "", "exact": true, "path": "/docs/tags/someTag", }, { "component": "", "path": "/docs", "routes": [ { "component": "", "exact": true, "path": "/docs/doc1", }, { "component": "", "exact": true, "path": "/docs/doc2", }, ], }, ], }, ] `;
2,287
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/translations
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/translations/__tests__/translations.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import fs from 'fs-extra'; import path from 'path'; import tmp from 'tmp-promise'; import { writePluginTranslations, writeCodeTranslations, readCodeTranslationFileContent, type WriteTranslationsOptions, localizePluginTranslationFile, getPluginsDefaultCodeTranslationMessages, applyDefaultCodeTranslations, } from '../translations'; import type { InitializedPlugin, LoadedPlugin, TranslationFile, TranslationFileContent, } from '@docusaurus/types'; async function createTmpSiteDir() { const {path: siteDirPath} = await tmp.dir({ prefix: 'jest-createTmpSiteDir', }); return siteDirPath; } async function createTmpTranslationFile( content: TranslationFileContent | null, ) { const siteDir = await createTmpSiteDir(); const filePath = path.join(siteDir, 'i18n/en/code.json'); // null means we don't want a file, just a filename if (content !== null) { await fs.outputFile(filePath, JSON.stringify(content, null, 2)); } return { localizationDir: path.join(siteDir, 'i18n/en'), readFile() { return fs.readJSON(filePath); }, }; } describe('writeCodeTranslations', () => { const consoleInfoMock = jest .spyOn(console, 'info') .mockImplementation(() => {}); beforeEach(() => { consoleInfoMock.mockClear(); }); it('creates new translation file', async () => { const {localizationDir, readFile} = await createTmpTranslationFile(null); await writeCodeTranslations( {localizationDir}, { key1: {message: 'key1 message'}, key2: {message: 'key2 message'}, key3: {message: 'key3 message'}, }, {}, ); await expect(readFile()).resolves.toEqual({ key1: {message: 'key1 message'}, key2: {message: 'key2 message'}, key3: {message: 'key3 message'}, }); expect(consoleInfoMock).toHaveBeenCalledWith( expect.stringMatching(/3.* translations will be written/), ); }); it('creates new translation file with prefix', async () => { const {localizationDir, readFile} = await createTmpTranslationFile(null); await writeCodeTranslations( {localizationDir}, { key1: {message: 'key1 message'}, key2: {message: 'key2 message'}, key3: {message: 'key3 message'}, }, { messagePrefix: 'PREFIX ', }, ); await expect(readFile()).resolves.toEqual({ key1: {message: 'PREFIX key1 message'}, key2: {message: 'PREFIX key2 message'}, key3: {message: 'PREFIX key3 message'}, }); expect(consoleInfoMock).toHaveBeenCalledWith( expect.stringMatching(/3.* translations will be written/), ); }); it('appends missing translations', async () => { const {localizationDir, readFile} = await createTmpTranslationFile({ key1: {message: 'key1 message'}, key2: {message: 'key2 message'}, key3: {message: 'key3 message'}, }); await writeCodeTranslations( {localizationDir}, { key1: {message: 'key1 message new'}, key2: {message: 'key2 message new'}, key3: {message: 'key3 message new'}, key4: {message: 'key4 message new'}, }, {}, ); await expect(readFile()).resolves.toEqual({ key1: {message: 'key1 message'}, key2: {message: 'key2 message'}, key3: {message: 'key3 message'}, key4: {message: 'key4 message new'}, }); expect(consoleInfoMock).toHaveBeenCalledWith( expect.stringMatching(/4.* translations will be written/), ); }); it('appends missing.* translations with prefix', async () => { const {localizationDir, readFile} = await createTmpTranslationFile({ key1: {message: 'key1 message'}, }); await writeCodeTranslations( {localizationDir}, { key1: {message: 'key1 message new'}, key2: {message: 'key2 message new'}, }, { messagePrefix: 'PREFIX ', }, ); await expect(readFile()).resolves.toEqual({ key1: {message: 'key1 message'}, key2: {message: 'PREFIX key2 message new'}, }); expect(consoleInfoMock).toHaveBeenCalledWith( expect.stringMatching(/2.* translations will be written/), ); }); it('overrides missing translations', async () => { const {localizationDir, readFile} = await createTmpTranslationFile({ key1: {message: 'key1 message'}, }); await writeCodeTranslations( {localizationDir}, { key1: {message: 'key1 message new'}, key2: {message: 'key2 message new'}, }, { override: true, }, ); await expect(readFile()).resolves.toEqual({ key1: {message: 'key1 message new'}, key2: {message: 'key2 message new'}, }); expect(consoleInfoMock).toHaveBeenCalledWith( expect.stringMatching(/2.* translations will be written/), ); }); it('overrides missing translations with prefix', async () => { const {localizationDir, readFile} = await createTmpTranslationFile({ key1: {message: 'key1 message'}, }); await writeCodeTranslations( {localizationDir}, { key1: {message: 'key1 message new'}, key2: {message: 'key2 message new'}, }, { override: true, messagePrefix: 'PREFIX ', }, ); await expect(readFile()).resolves.toEqual({ key1: {message: 'PREFIX key1 message new'}, key2: {message: 'PREFIX key2 message new'}, }); expect(consoleInfoMock).toHaveBeenCalledWith( expect.stringMatching(/2.* translations will be written/), ); }); it('always overrides message description', async () => { const {localizationDir, readFile} = await createTmpTranslationFile({ key1: {message: 'key1 message', description: 'key1 desc'}, key2: {message: 'key2 message', description: 'key2 desc'}, key3: {message: 'key3 message', description: undefined}, }); await writeCodeTranslations( {localizationDir}, { key1: {message: 'key1 message new', description: undefined}, key2: {message: 'key2 message new', description: 'key2 desc new'}, key3: {message: 'key3 message new', description: 'key3 desc new'}, }, {}, ); await expect(readFile()).resolves.toEqual({ key1: {message: 'key1 message', description: undefined}, key2: {message: 'key2 message', description: 'key2 desc new'}, key3: {message: 'key3 message', description: 'key3 desc new'}, }); expect(consoleInfoMock).toHaveBeenCalledWith( expect.stringMatching(/3.* translations will be written/), ); }); it('does not create empty translation files', async () => { const {localizationDir, readFile} = await createTmpTranslationFile(null); await writeCodeTranslations({localizationDir}, {}, {}); await expect(readFile()).rejects.toThrow( /ENOENT: no such file or directory, open /, ); expect(consoleInfoMock).toHaveBeenCalledTimes(0); }); it('throws for invalid content', async () => { const {localizationDir} = await createTmpTranslationFile( // @ts-expect-error: bad content on purpose {bad: 'content'}, ); await expect(() => writeCodeTranslations( {localizationDir}, { key1: {message: 'key1 message'}, }, {}, ), ).rejects.toThrowErrorMatchingInlineSnapshot( `""bad" must be of type object"`, ); }); }); describe('writePluginTranslations', () => { it('writes plugin translations', async () => { const localizationDir = await createTmpSiteDir(); const filePath = path.join( localizationDir, 'my-plugin-name', 'my/translation/file.json', ); await writePluginTranslations({ localizationDir, translationFile: { path: 'my/translation/file', content: { key1: {message: 'key1 message'}, key2: {message: 'key2 message'}, key3: {message: 'key3 message'}, }, }, plugin: { name: 'my-plugin-name', options: { id: 'default', }, } as LoadedPlugin, }); await expect(fs.readJSON(filePath)).resolves.toEqual({ key1: {message: 'key1 message'}, key2: {message: 'key2 message'}, key3: {message: 'key3 message'}, }); }); it('writes plugin translations consecutively with different options', async () => { const localizationDir = await createTmpSiteDir(); const filePath = path.join( localizationDir, 'my-plugin-name-my-plugin-id', 'my/translation/file.json', ); function doWritePluginTranslations( content: TranslationFileContent, options?: WriteTranslationsOptions, ) { return writePluginTranslations({ localizationDir, locale: 'fr', translationFile: { path: 'my/translation/file', content, }, // @ts-expect-error: enough for this test plugin: { name: 'my-plugin-name', options: { id: 'my-plugin-id', }, }, options, }); } await doWritePluginTranslations({ key1: {message: 'key1 message', description: 'key1 desc'}, key2: {message: 'key2 message', description: 'key2 desc'}, key3: {message: 'key3 message', description: 'key3 desc'}, }); await expect(fs.readJSON(filePath)).resolves.toEqual({ key1: {message: 'key1 message', description: 'key1 desc'}, key2: {message: 'key2 message', description: 'key2 desc'}, key3: {message: 'key3 message', description: 'key3 desc'}, }); await doWritePluginTranslations( { key3: {message: 'key3 message 2'}, key4: {message: 'key4 message 2', description: 'key4 desc'}, }, {messagePrefix: 'PREFIX '}, ); await expect(fs.readJSON(filePath)).resolves.toEqual({ key1: {message: 'key1 message', description: 'key1 desc'}, key2: {message: 'key2 message', description: 'key2 desc'}, key3: {message: 'key3 message', description: undefined}, key4: {message: 'PREFIX key4 message 2', description: 'key4 desc'}, }); await doWritePluginTranslations( { key1: {message: 'key1 message 3', description: 'key1 desc'}, key2: {message: 'key2 message 3', description: 'key2 desc'}, key3: {message: 'key3 message 3', description: 'key3 desc'}, key4: {message: 'key4 message 3', description: 'key4 desc'}, }, {messagePrefix: 'PREFIX ', override: true}, ); await expect(fs.readJSON(filePath)).resolves.toEqual({ key1: {message: 'PREFIX key1 message 3', description: 'key1 desc'}, key2: {message: 'PREFIX key2 message 3', description: 'key2 desc'}, key3: {message: 'PREFIX key3 message 3', description: 'key3 desc'}, key4: {message: 'PREFIX key4 message 3', description: 'key4 desc'}, }); }); it('throws with explicit extension', async () => { const localizationDir = await createTmpSiteDir(); await expect(() => writePluginTranslations({ localizationDir, translationFile: { path: 'my/translation/file.json', content: {}, }, plugin: { name: 'my-plugin-name', options: { id: 'my-plugin-id', }, } as LoadedPlugin, options: {}, }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Translation file path at "my/translation/file.json" does not need to end with ".json", we add the extension automatically."`, ); }); }); describe('localizePluginTranslationFile', () => { it('does not localize if localized file does not exist', async () => { const localizationDir = await createTmpSiteDir(); const translationFile: TranslationFile = { path: 'my/translation/file', content: { key1: {message: 'key1 message'}, key2: {message: 'key2 message'}, key3: {message: 'key3 message'}, }, }; const localizedTranslationFile = await localizePluginTranslationFile({ localizationDir, translationFile, plugin: { name: 'my-plugin-name', options: {}, } as LoadedPlugin, }); expect(localizedTranslationFile).toEqual(translationFile); }); it('normalizes partially localized translation files', async () => { const localizationDir = await createTmpSiteDir(); await fs.outputJSON( path.join(localizationDir, 'my-plugin-name', 'my/translation/file.json'), { key2: {message: 'key2 message localized'}, key4: {message: 'key4 message localized'}, }, ); const translationFile: TranslationFile = { path: 'my/translation/file', content: { key1: {message: 'key1 message'}, key2: {message: 'key2 message'}, key3: {message: 'key3 message'}, }, }; const localizedTranslationFile = await localizePluginTranslationFile({ localizationDir, translationFile, plugin: { name: 'my-plugin-name', options: {}, } as LoadedPlugin, }); expect(localizedTranslationFile).toEqual({ path: translationFile.path, content: { // We only append/override localized messages, but never delete the data // of the unlocalized translation file. This ensures that all required // keys are present when trying to read the translations files key1: {message: 'key1 message'}, key2: {message: 'key2 message localized'}, key3: {message: 'key3 message'}, key4: {message: 'key4 message localized'}, }, }); }); }); describe('readCodeTranslationFileContent', () => { async function testReadTranslation(val: TranslationFileContent) { const {localizationDir} = await createTmpTranslationFile(val); return readCodeTranslationFileContent({localizationDir}); } it("returns undefined if file does't exist", async () => { await expect( readCodeTranslationFileContent({localizationDir: 'foo'}), ).resolves.toBeUndefined(); }); it('passes valid translation file content', async () => { await expect(testReadTranslation({})).resolves.toEqual({}); await expect(testReadTranslation({key1: {message: ''}})).resolves.toEqual({ key1: {message: ''}, }); await expect( testReadTranslation({key1: {message: 'abc', description: 'desc'}}), ).resolves.toEqual({key1: {message: 'abc', description: 'desc'}}); await expect( testReadTranslation({ key1: {message: 'abc', description: 'desc'}, key2: {message: 'def', description: 'desc'}, }), ).resolves.toEqual({ key1: {message: 'abc', description: 'desc'}, key2: {message: 'def', description: 'desc'}, }); }); it('fails for invalid translation file content', async () => { await expect(() => // @ts-expect-error: test testReadTranslation('HEY'), ).rejects.toThrowErrorMatchingInlineSnapshot( `""value" must be of type object"`, ); await expect(() => // @ts-expect-error: test testReadTranslation(42), ).rejects.toThrowErrorMatchingInlineSnapshot( `""value" must be of type object"`, ); await expect(() => // @ts-expect-error: test testReadTranslation({key: {description: 'no message'}}), ).rejects.toThrowErrorMatchingInlineSnapshot(`""key.message" is required"`); await expect(() => // @ts-expect-error: test testReadTranslation({key: {message: 42}}), ).rejects.toThrowErrorMatchingInlineSnapshot( `""key.message" must be a string"`, ); await expect(() => testReadTranslation({ // @ts-expect-error: test key: {message: 'Message', description: 42}, }), ).rejects.toThrowErrorMatchingInlineSnapshot( `""key.description" must be a string"`, ); }); }); describe('getPluginsDefaultCodeTranslationMessages', () => { function createTestPlugin( fn: InitializedPlugin['getDefaultCodeTranslationMessages'], ): InitializedPlugin { return {getDefaultCodeTranslationMessages: fn} as InitializedPlugin; } it('works for empty plugins', async () => { const plugins: InitializedPlugin[] = []; await expect( getPluginsDefaultCodeTranslationMessages(plugins), ).resolves.toEqual({}); }); it('works for 1 plugin without lifecycle', async () => { const plugins: InitializedPlugin[] = [createTestPlugin(undefined)]; await expect( getPluginsDefaultCodeTranslationMessages(plugins), ).resolves.toEqual({}); }); it('works for 1 plugin with lifecycle', async () => { const plugins: InitializedPlugin[] = [ createTestPlugin(async () => ({ a: '1', b: '2', })), ]; await expect( getPluginsDefaultCodeTranslationMessages(plugins), ).resolves.toEqual({ a: '1', b: '2', }); }); it('works for 2 plugins with lifecycles', async () => { const plugins: InitializedPlugin[] = [ createTestPlugin(async () => ({ a: '1', b: '2', })), createTestPlugin(async () => ({ c: '3', d: '4', })), ]; await expect( getPluginsDefaultCodeTranslationMessages(plugins), ).resolves.toEqual({ a: '1', b: '2', c: '3', d: '4', }); }); it('works for realistic use-case', async () => { const plugins: InitializedPlugin[] = [ createTestPlugin(undefined), createTestPlugin(async () => ({ a: '1', b: '2', })), createTestPlugin(undefined), createTestPlugin(undefined), createTestPlugin(async () => ({ a: '2', d: '4', })), createTestPlugin(async () => ({ d: '5', })), createTestPlugin(undefined), ]; await expect( getPluginsDefaultCodeTranslationMessages(plugins), ).resolves.toEqual({ // merge, last plugin wins b: '2', a: '2', d: '5', }); }); }); describe('applyDefaultCodeTranslations', () => { const consoleWarnMock = jest .spyOn(console, 'warn') .mockImplementation(() => {}); beforeEach(() => { consoleWarnMock.mockClear(); }); it('works for no code and message', () => { expect( applyDefaultCodeTranslations({ extractedCodeTranslations: {}, defaultCodeMessages: {}, }), ).toEqual({}); expect(consoleWarnMock).toHaveBeenCalledTimes(0); }); it('works for code and message', () => { expect( applyDefaultCodeTranslations({ extractedCodeTranslations: { id: { message: 'extracted message', description: 'description', }, }, defaultCodeMessages: { id: 'default message', }, }), ).toEqual({ id: { message: 'default message', description: 'description', }, }); expect(consoleWarnMock).toHaveBeenCalledTimes(0); }); it('works for code and message mismatch', () => { expect( applyDefaultCodeTranslations({ extractedCodeTranslations: { id: { message: 'extracted message', description: 'description', }, }, defaultCodeMessages: { unknownId: 'default message', }, }), ).toEqual({ id: { message: 'extracted message', description: 'description', }, }); expect(consoleWarnMock).toHaveBeenCalledTimes(1); expect(consoleWarnMock.mock.calls[0]![0]).toMatch(/unknownId/); }); it('works for realistic scenario', () => { expect( applyDefaultCodeTranslations({ extractedCodeTranslations: { id1: { message: 'extracted message 1', description: 'description 1', }, id2: { message: 'extracted message 2', description: 'description 2', }, id3: { message: 'extracted message 3', description: 'description 3', }, }, defaultCodeMessages: { id2: 'default message id2', id3: 'default message id3', idUnknown1: 'default message idUnknown1', idUnknown2: 'default message idUnknown2', }, }), ).toEqual({ id1: { message: 'extracted message 1', description: 'description 1', }, id2: { message: 'default message id2', description: 'description 2', }, id3: { message: 'default message id3', description: 'description 3', }, }); expect(consoleWarnMock).toHaveBeenCalledTimes(1); expect(consoleWarnMock.mock.calls[0]![0]).toMatch(/idUnknown1/); expect(consoleWarnMock.mock.calls[0]![0]).toMatch(/idUnknown2/); }); });
2,288
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/translations
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/translations/__tests__/translationsExtractor.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import path from 'path'; import fs from 'fs-extra'; import tmp from 'tmp-promise'; import {SRC_DIR_NAME} from '@docusaurus/utils'; import { extractSourceCodeFileTranslations, extractSiteSourceCodeTranslations, } from '../translationsExtractor'; import {getBabelOptions} from '../../../webpack/utils'; import type {InitializedPlugin, LoadedPlugin} from '@docusaurus/types'; const TestBabelOptions = getBabelOptions({ isServer: true, }); async function createTmpDir() { const {path: siteDirPath} = await tmp.dir({ prefix: 'jest-createTmpSiteDir', }); return siteDirPath; } async function createTmpSourceCodeFile({ extension, content, }: { extension: string; content: string; }) { const file = await tmp.file({ prefix: 'jest-createTmpSourceCodeFile', postfix: `.${extension}`, }); await fs.writeFile(file.path, content); return { sourceCodeFilePath: file.path, }; } describe('extractSourceCodeFileTranslations', () => { it('throws for bad source code', async () => { const {sourceCodeFilePath} = await createTmpSourceCodeFile({ extension: 'js', content: ` const default => { } `, }); const errorMock = jest.spyOn(console, 'error').mockImplementation(() => {}); await expect( extractSourceCodeFileTranslations(sourceCodeFilePath, TestBabelOptions), ).rejects.toThrow(); expect(errorMock).toHaveBeenCalledWith( expect.stringMatching( /Error while attempting to extract Docusaurus translations from source code file at/, ), ); }); it('extracts nothing from untranslated source code', async () => { const {sourceCodeFilePath} = await createTmpSourceCodeFile({ extension: 'js', content: ` const unrelated = 42; `, }); const sourceCodeFileTranslations = await extractSourceCodeFileTranslations( sourceCodeFilePath, TestBabelOptions, ); expect(sourceCodeFileTranslations).toEqual({ sourceCodeFilePath, translations: {}, warnings: [], }); }); it('extracts from a translate() functions calls', async () => { const {sourceCodeFilePath} = await createTmpSourceCodeFile({ extension: 'js', content: ` import {translate} from '@docusaurus/Translate'; export default function MyComponent() { return ( <div> <input text={translate({id: 'codeId',message: 'code message',description: 'code description'})}/> <input text={translate({id: 'codeId1'})}/> </div> ); } `, }); const sourceCodeFileTranslations = await extractSourceCodeFileTranslations( sourceCodeFilePath, TestBabelOptions, ); expect(sourceCodeFileTranslations).toEqual({ sourceCodeFilePath, translations: { codeId: {message: 'code message', description: 'code description'}, codeId1: {message: 'codeId1'}, }, warnings: [], }); }); it('extracts from a <Translate> components', async () => { const {sourceCodeFilePath} = await createTmpSourceCodeFile({ extension: 'js', content: ` import Translate from '@docusaurus/Translate'; export default function MyComponent() { return ( <div> <Translate id="codeId" description={"code description"}> code message </Translate> <Translate id="codeId1" description="description 2" /> </div> ); } `, }); const sourceCodeFileTranslations = await extractSourceCodeFileTranslations( sourceCodeFilePath, TestBabelOptions, ); expect(sourceCodeFileTranslations).toEqual({ sourceCodeFilePath, translations: { codeId: {message: 'code message', description: 'code description'}, codeId1: {message: 'codeId1', description: 'description 2'}, }, warnings: [], }); }); it('extracts statically evaluable content', async () => { const {sourceCodeFilePath} = await createTmpSourceCodeFile({ extension: 'js', content: ` import Translate, {translate} from '@docusaurus/Translate'; const prefix = "prefix "; export default function MyComponent() { return ( <div> <input text={translate({ id: prefix + 'codeId fn', message: prefix + 'code message', description: prefix + 'code description'} )} /> <Translate id={prefix + "codeId comp"} description={prefix + "code description"} > {prefix + "code message"} </Translate> <Translate> { prefix + \`Static template literal with unusual formatting!\` } </Translate> </div> ); } `, }); const sourceCodeFileTranslations = await extractSourceCodeFileTranslations( sourceCodeFilePath, TestBabelOptions, ); expect(sourceCodeFileTranslations).toEqual({ sourceCodeFilePath, translations: { 'prefix codeId comp': { message: 'prefix code message', description: 'prefix code description', }, 'prefix codeId fn': { message: 'prefix code message', description: 'prefix code description', }, 'prefix Static template literal with unusual formatting!': { message: 'prefix Static template literal with unusual formatting!', }, }, warnings: [], }); }); it('extracts from TypeScript file', async () => { const {sourceCodeFilePath} = await createTmpSourceCodeFile({ extension: 'tsx', content: ` import {translate} from '@docusaurus/Translate'; type ComponentProps<T> = {toto: string} export default function MyComponent<T>(props: ComponentProps<T>) { return ( <div> <input text={translate({id: 'codeId',message: 'code message',description: 'code description'}) as string}/> <input text={translate({message: 'code message 2',description: 'code description 2'}) as string}/> </div> ); } `, }); const sourceCodeFileTranslations = await extractSourceCodeFileTranslations( sourceCodeFilePath, TestBabelOptions, ); expect(sourceCodeFileTranslations).toEqual({ sourceCodeFilePath, translations: { codeId: {message: 'code message', description: 'code description'}, 'code message 2': { message: 'code message 2', description: 'code description 2', }, }, warnings: [], }); }); it('does not extract from functions that is not docusaurus provided', async () => { const {sourceCodeFilePath} = await createTmpSourceCodeFile({ extension: 'js', content: ` import translate from 'a-lib'; export default function somethingElse() { const a = translate('foo'); return <Translate>bar</Translate> } `, }); const sourceCodeFileTranslations = await extractSourceCodeFileTranslations( sourceCodeFilePath, TestBabelOptions, ); expect(sourceCodeFileTranslations).toEqual({ sourceCodeFilePath, translations: {}, warnings: [], }); }); it('does not extract from functions that is internal', async () => { const {sourceCodeFilePath} = await createTmpSourceCodeFile({ extension: 'js', content: ` function translate() { return 'foo' } export default function somethingElse() { const a = translate('foo'); return a; } `, }); const sourceCodeFileTranslations = await extractSourceCodeFileTranslations( sourceCodeFilePath, TestBabelOptions, ); expect(sourceCodeFileTranslations).toEqual({ sourceCodeFilePath, translations: {}, warnings: [], }); }); it('recognizes aliased imports', async () => { const {sourceCodeFilePath} = await createTmpSourceCodeFile({ extension: 'js', content: ` import Foo, {translate as bar} from '@docusaurus/Translate'; export function MyComponent() { return ( <div> <Foo id="codeId" description={"code description"}> code message </Foo> <Translate id="codeId1" /> </div> ); } export default function () { return ( <div> <input text={translate({id: 'codeId',message: 'code message',description: 'code description'})}/> <input text={bar({id: 'codeId1'})}/> </div> ); } `, }); const sourceCodeFileTranslations = await extractSourceCodeFileTranslations( sourceCodeFilePath, TestBabelOptions, ); expect(sourceCodeFileTranslations).toEqual({ sourceCodeFilePath, translations: { codeId: { description: 'code description', message: 'code message', }, codeId1: { message: 'codeId1', }, }, warnings: [], }); }); it('recognizes aliased imports as string literal', async () => { const {sourceCodeFilePath} = await createTmpSourceCodeFile({ extension: 'js', content: ` import {'translate' as bar} from '@docusaurus/Translate'; export default function () { return ( <div> <input text={translate({id: 'codeId',message: 'code message',description: 'code description'})}/> <input text={bar({id: 'codeId1'})}/> </div> ); } `, }); const sourceCodeFileTranslations = await extractSourceCodeFileTranslations( sourceCodeFilePath, TestBabelOptions, ); expect(sourceCodeFileTranslations).toEqual({ sourceCodeFilePath, translations: { codeId1: { message: 'codeId1', }, }, warnings: [], }); }); it('warns about id if no children', async () => { const {sourceCodeFilePath} = await createTmpSourceCodeFile({ extension: 'js', content: ` import Translate from '@docusaurus/Translate'; export default function () { return ( <Translate description="foo" /> ); } `, }); const sourceCodeFileTranslations = await extractSourceCodeFileTranslations( sourceCodeFilePath, TestBabelOptions, ); expect(sourceCodeFileTranslations).toEqual({ sourceCodeFilePath, translations: {}, warnings: [ `<Translate> without children must have id prop. Example: <Translate id="my-id" /> File: ${sourceCodeFilePath} at line 6 Full code: <Translate description="foo" />`, ], }); }); it('warns about dynamic id', async () => { const {sourceCodeFilePath} = await createTmpSourceCodeFile({ extension: 'js', content: ` import Translate from '@docusaurus/Translate'; export default function () { return ( <Translate id={index}>foo</Translate> ); } `, }); const sourceCodeFileTranslations = await extractSourceCodeFileTranslations( sourceCodeFilePath, TestBabelOptions, ); expect(sourceCodeFileTranslations).toEqual({ sourceCodeFilePath, translations: { foo: { message: 'foo', }, }, warnings: [ `<Translate> prop=id should be a statically evaluable object. Example: <Translate id="optional id" description="optional description">Message</Translate> Dynamically constructed values are not allowed, because they prevent translations to be extracted. File: ${sourceCodeFilePath} at line 6 Full code: <Translate id={index}>foo</Translate>`, ], }); }); it('warns about dynamic children', async () => { const {sourceCodeFilePath} = await createTmpSourceCodeFile({ extension: 'js', content: ` import Translate from '@docusaurus/Translate'; export default function () { return ( <Translate id='foo'><a>hhh</a></Translate> ); } `, }); const sourceCodeFileTranslations = await extractSourceCodeFileTranslations( sourceCodeFilePath, TestBabelOptions, ); expect(sourceCodeFileTranslations).toEqual({ sourceCodeFilePath, translations: {}, warnings: [ `Translate content could not be extracted. It has to be a static string and use optional but static props, like <Translate id="my-id" description="my-description">text</Translate>. File: ${sourceCodeFilePath} at line 6 Full code: <Translate id='foo'><a>hhh</a></Translate>`, ], }); }); it('warns about dynamic translate argument', async () => { const {sourceCodeFilePath} = await createTmpSourceCodeFile({ extension: 'js', content: ` import {translate} from '@docusaurus/Translate'; translate(foo); `, }); const sourceCodeFileTranslations = await extractSourceCodeFileTranslations( sourceCodeFilePath, TestBabelOptions, ); expect(sourceCodeFileTranslations).toEqual({ sourceCodeFilePath, translations: {}, warnings: [ `translate() first arg should be a statically evaluable object. Example: translate({message: "text",id: "optional.id",description: "optional description"} Dynamically constructed values are not allowed, because they prevent translations to be extracted. File: ${sourceCodeFilePath} at line 4 Full code: translate(foo)`, ], }); }); it('warns about too many arguments', async () => { const {sourceCodeFilePath} = await createTmpSourceCodeFile({ extension: 'js', content: ` import {translate} from '@docusaurus/Translate'; translate({message: 'a'}, {a: 1}, 2); `, }); const sourceCodeFileTranslations = await extractSourceCodeFileTranslations( sourceCodeFilePath, TestBabelOptions, ); expect(sourceCodeFileTranslations).toEqual({ sourceCodeFilePath, translations: {}, warnings: [ `translate() function only takes 1 or 2 args File: ${sourceCodeFilePath} at line 4 Full code: translate({ message: 'a' }, { a: 1 }, 2)`, ], }); }); }); describe('extractSiteSourceCodeTranslations', () => { it('extracts translation from all plugins source code', async () => { const siteDir = await createTmpDir(); const siteComponentFile1 = path.join( siteDir, SRC_DIR_NAME, 'site-component-1.jsx', ); await fs.outputFile( siteComponentFile1, ` import Translate from '@docusaurus/Translate'; export default function MySiteComponent1() { return ( <Translate id="siteComponentFileId1" description="site component 1 desc" > site component 1 message </Translate> ); } `, ); function createTestPlugin(pluginDir: string): InitializedPlugin { // @ts-expect-error: good enough for this test return { name: 'abc', getPathsToWatch() { return [path.join(pluginDir, 'subpath', '**/*.{js,jsx,ts,tsx}')]; }, getThemePath() { return path.join(pluginDir, 'src', 'theme'); }, }; } const plugin1Dir = await createTmpDir(); const plugin1File1 = path.join(plugin1Dir, 'subpath', 'file1.jsx'); await fs.outputFile( plugin1File1, ` import {translate} from '@docusaurus/Translate'; export default function MyComponent() { return ( <div> <input text={translate( {id: 'plugin1Id1',message: 'plugin1 message 1',description: 'plugin1 description 1'}, {someDynamicValue: 42} )}/> </div> ); } `, ); const plugin1File2 = path.join(plugin1Dir, 'src', 'theme', 'file2.jsx'); await fs.outputFile( plugin1File2, ` import {translate} from '@docusaurus/Translate'; export default function MyComponent() { return ( <div> <input text={translate({id: 'plugin1Id2',message: 'plugin1 message 2',description: 'plugin1 description 2'})}/> </div> ); } `, ); // This one should not be found! On purpose! const plugin1File3 = path.join(plugin1Dir, 'ignoredFolder', 'file3.jsx'); await fs.outputFile( plugin1File3, ` import {translate} from '@docusaurus/Translate'; export default function MyComponent() { return ( <div> <input text={translate({id: 'plugin1Id3',message: 'plugin1 message 3',description: 'plugin1 description 3'})}/> </div> ); } `, ); const plugin1File4 = path.join(plugin1Dir, 'src/theme/file4.jsx'); // Contains some invalid translations... await fs.outputFile( plugin1File4, ` import {translate} from '@docusaurus/Translate'; export default function MyComponent() { return ( <div> <input text={translate({id: index})}/> </div> ); } `, ); const consoleWarnMock = jest .spyOn(console, 'warn') .mockImplementation(() => {}); const plugin1 = createTestPlugin(plugin1Dir); const plugin2Dir = await createTmpDir(); const plugin2File = path.join(plugin1Dir, 'subpath', 'file.tsx'); await fs.outputFile( plugin2File, ` import Translate, {translate} from '@docusaurus/Translate'; type Props = {hey: string}; export default function MyComponent(props: Props) { return ( <div> <input text={translate({id: 'plugin2Id1',message: 'plugin2 message 1',description: 'plugin2 description 1'})}/> <Translate id="plugin2Id2" description="plugin2 description 2" > plugin2 message 2 </Translate> </div> ); } `, ); const plugin2 = createTestPlugin(plugin2Dir); const plugins = [ plugin1, plugin2, {name: 'dummy', options: {}, version: {type: 'synthetic'}} as const, ] as LoadedPlugin[]; const translations = await extractSiteSourceCodeTranslations( siteDir, plugins, TestBabelOptions, ); expect(translations).toEqual({ siteComponentFileId1: { description: 'site component 1 desc', message: 'site component 1 message', }, plugin1Id1: { description: 'plugin1 description 1', message: 'plugin1 message 1', }, plugin1Id2: { description: 'plugin1 description 2', message: 'plugin1 message 2', }, plugin2Id1: { description: 'plugin2 description 1', message: 'plugin2 message 1', }, plugin2Id2: { description: 'plugin2 description 2', message: 'plugin2 message 2', }, }); expect(consoleWarnMock.mock.calls[0]![0]).toMatch( /.*\[WARNING\].* Translation extraction warnings for file .*src.theme.file4\.jsx.*\n.*- translate\(\) first arg should be a statically evaluable object\./, ); }); });
2,293
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/webpack
petrpan-code/facebook/docusaurus/packages/docusaurus/src/webpack/__tests__/base.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import path from 'path'; import _ from 'lodash'; import * as utils from '@docusaurus/utils/lib/webpackUtils'; import {posixPath} from '@docusaurus/utils'; import {excludeJS, clientDir, createBaseConfig} from '../base'; import type {Props} from '@docusaurus/types'; describe('babel transpilation exclude logic', () => { it('always transpiles client dir files', () => { const clientFiles = [ 'App.js', 'clientEntry.js', 'serverEntry.js', path.join('exports', 'Link.js'), ]; clientFiles.forEach((file) => { expect(excludeJS(path.join(clientDir, file))).toBe(false); }); }); it('always transpiles non node_module files', () => { const moduleFiles = [ '/pages/user/App.jsx', '/website/src/components/foo.js', '/src/theme/SearchBar/index.js', ]; moduleFiles.forEach((file) => { expect(excludeJS(file)).toBe(false); }); }); it('transpiles docusaurus npm packages even in node_modules', () => { const moduleFiles = [ '/website/node_modules/docusaurus-theme-search/theme/Navbar/index.js', 'node_modules/@docusaurus/theme-classic/theme/Layout.js', '/docusaurus/website/node_modules/@docusaurus/theme-search-algolia/theme/SearchBar.js', ]; moduleFiles.forEach((file) => { expect(excludeJS(file)).toBe(false); }); }); it('does not transpile node_modules', () => { const moduleFiles = [ 'node_modules/react-toggle.js', '/website/node_modules/react-trend/index.js', '/docusaurus/website/node_modules/react-super.js', '/docusaurus/website/node_modules/@docusaurus/core/node_modules/core-js/modules/_descriptors.js', 'node_modules/docusaurus-theme-classic/node_modules/react-slick/index.js', ]; moduleFiles.forEach((file) => { expect(excludeJS(file)).toBe(true); }); }); }); describe('base webpack config', () => { const props = { outDir: '', siteDir: path.resolve(__dirname, '__fixtures__', 'base_test_site'), siteConfig: {staticDirectories: ['static']}, baseUrl: '', generatedFilesDir: '', routesPaths: [''], i18n: { currentLocale: 'en', }, siteMetadata: { docusaurusVersion: '2.0.0-alpha.70', }, plugins: [ { getThemePath() { return path.resolve( __dirname, '__fixtures__', 'base_test_site', 'pluginThemeFolder', ); }, }, { getThemePath() { return path.resolve( __dirname, '__fixtures__', 'base_test_site', 'secondPluginThemeFolder', ); }, }, ], } as Props; afterEach(() => { jest.restoreAllMocks(); }); it('creates webpack aliases', async () => { const aliases = ((await createBaseConfig(props, true)).resolve?.alias ?? {}) as {[alias: string]: string}; // Make aliases relative so that test work on all computers const relativeAliases = _.mapValues(aliases, (a) => posixPath(path.relative(props.siteDir, a)), ); expect(relativeAliases).toMatchSnapshot(); }); it('uses svg rule', async () => { const fileLoaderUtils = utils.getFileLoaderUtils(); const mockSvg = jest.spyOn(fileLoaderUtils.rules, 'svg'); jest .spyOn(utils, 'getFileLoaderUtils') .mockImplementation(() => fileLoaderUtils); await createBaseConfig(props, false, false); expect(mockSvg).toHaveBeenCalled(); }); });
2,294
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/webpack
petrpan-code/facebook/docusaurus/packages/docusaurus/src/webpack/__tests__/client.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import webpack from 'webpack'; import createClientConfig from '../client'; import {loadSetup} from '../../server/__tests__/testUtils'; describe('webpack dev config', () => { it('simple', async () => { const props = await loadSetup('simple-site'); const config = await createClientConfig(props); const errors = webpack.validate(config); expect(errors).toBeUndefined(); }); it('custom', async () => { const props = await loadSetup('custom-site'); const config = await createClientConfig(props); const errors = webpack.validate(config); expect(errors).toBeUndefined(); }); });
2,295
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/webpack
petrpan-code/facebook/docusaurus/packages/docusaurus/src/webpack/__tests__/server.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import webpack from 'webpack'; import createServerConfig from '../server'; import {loadSetup} from '../../server/__tests__/testUtils'; describe('webpack production config', () => { it('simple', async () => { jest.spyOn(console, 'log').mockImplementation(() => {}); const props = await loadSetup('simple-site'); const config = await createServerConfig({ props, onHeadTagsCollected: () => {}, onLinksCollected: () => {}, }); const errors = webpack.validate(config); expect(errors).toBeUndefined(); }); it('custom', async () => { jest.spyOn(console, 'log').mockImplementation(() => {}); const props = await loadSetup('custom-site'); const config = await createServerConfig({ props, onHeadTagsCollected: () => {}, onLinksCollected: () => {}, }); const errors = webpack.validate(config); expect(errors).toBeUndefined(); }); });
2,296
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/webpack
petrpan-code/facebook/docusaurus/packages/docusaurus/src/webpack/__tests__/utils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import webpack, {type Configuration, type RuleSetRule} from 'webpack'; import { getCustomizableJSLoader, applyConfigureWebpack, applyConfigurePostCss, getHttpsConfig, } from '../utils'; import type {Plugin} from '@docusaurus/types'; describe('customize JS loader', () => { it('getCustomizableJSLoader defaults to babel loader', () => { expect(getCustomizableJSLoader()({isServer: true}).loader).toBe( require.resolve('babel-loader'), ); expect(getCustomizableJSLoader()({isServer: false}).loader).toBe( require.resolve('babel-loader'), ); }); it('getCustomizableJSLoader accepts loaders with preset', () => { expect(getCustomizableJSLoader('babel')({isServer: true}).loader).toBe( require.resolve('babel-loader'), ); expect(getCustomizableJSLoader('babel')({isServer: false}).loader).toBe( require.resolve('babel-loader'), ); }); it('getCustomizableJSLoader allows customization', () => { const customJSLoader = (isServer: boolean): RuleSetRule => ({ loader: 'my-fast-js-loader', options: String(isServer), }); expect(getCustomizableJSLoader(customJSLoader)({isServer: true})).toEqual( customJSLoader(true), ); expect(getCustomizableJSLoader(customJSLoader)({isServer: false})).toEqual( customJSLoader(false), ); }); }); describe('extending generated webpack config', () => { it('direct mutation on generated webpack config object', async () => { // Fake generated webpack config let config: Configuration = { output: { path: __dirname, filename: 'bundle.js', }, }; // @ts-expect-error: Testing an edge-case that we did not write types for const configureWebpack: NonNullable<Plugin['configureWebpack']> = ( generatedConfig, isServer, ) => { if (!isServer) { generatedConfig.entry = 'entry.js'; generatedConfig.output = { path: path.join(__dirname, 'dist'), filename: 'new.bundle.js', }; } // Implicitly returning undefined to test null-safety }; config = applyConfigureWebpack(configureWebpack, config, false, undefined, { content: 42, }); expect(config).toEqual({ entry: 'entry.js', output: { path: path.join(__dirname, 'dist'), filename: 'new.bundle.js', }, }); const errors = webpack.validate(config); expect(errors).toBeUndefined(); }); it('webpack-merge with user webpack config object', async () => { let config: Configuration = { output: { path: __dirname, filename: 'bundle.js', }, }; const configureWebpack: Plugin['configureWebpack'] = () => ({ entry: 'entry.js', output: { path: path.join(__dirname, 'dist'), filename: 'new.bundle.js', }, }); config = applyConfigureWebpack(configureWebpack, config, false, undefined, { content: 42, }); expect(config).toEqual({ entry: 'entry.js', output: { path: path.join(__dirname, 'dist'), filename: 'new.bundle.js', }, }); const errors = webpack.validate(config); expect(errors).toBeUndefined(); }); it('webpack-merge with custom strategy', async () => { const config: Configuration = { module: { rules: [{use: 'xxx'}, {use: 'yyy'}], }, }; const createConfigureWebpack = (mergeStrategy?: { [key: string]: 'prepend' | 'append'; }): NonNullable<Plugin['configureWebpack']> => () => ({ module: { rules: [{use: 'zzz'}], }, mergeStrategy, }); const defaultStrategyMergeConfig = applyConfigureWebpack( createConfigureWebpack(), config, false, undefined, {content: 42}, ); expect(defaultStrategyMergeConfig).toEqual({ module: { rules: [{use: 'xxx'}, {use: 'yyy'}, {use: 'zzz'}], }, }); const prependRulesStrategyConfig = applyConfigureWebpack( createConfigureWebpack({'module.rules': 'prepend'}), config, false, undefined, {content: 42}, ); expect(prependRulesStrategyConfig).toEqual({ module: { rules: [{use: 'zzz'}, {use: 'xxx'}, {use: 'yyy'}], }, }); const uselessMergeStrategyConfig = applyConfigureWebpack( createConfigureWebpack({uselessAttributeName: 'append'}), config, false, undefined, {content: 42}, ); expect(uselessMergeStrategyConfig).toEqual({ module: { rules: [{use: 'xxx'}, {use: 'yyy'}, {use: 'zzz'}], }, }); }); }); describe('extending PostCSS', () => { it('user plugin should be appended in PostCSS loader', () => { let webpackConfig: Configuration = { output: { path: __dirname, filename: 'bundle.js', }, module: { rules: [ { test: 'any', use: [ { loader: 'some-loader-1', options: {}, }, { loader: 'some-loader-2', options: {}, }, { loader: 'postcss-loader-1', options: { postcssOptions: { plugins: [['default-postcss-loader-1-plugin']], }, }, }, { loader: 'some-loader-3', options: {}, }, ], }, { test: '2nd-test', use: [ { loader: 'postcss-loader-2', options: { postcssOptions: { plugins: [['default-postcss-loader-2-plugin']], }, }, }, ], }, ], }, }; function createFakePlugin(name: string) { return [name, {}]; } // Run multiple times: ensure last run does not override previous runs webpackConfig = applyConfigurePostCss( (postCssOptions) => ({ ...postCssOptions, plugins: [ ...postCssOptions.plugins, createFakePlugin('postcss-plugin-1'), ], }), webpackConfig, ); webpackConfig = applyConfigurePostCss( (postCssOptions) => ({ ...postCssOptions, plugins: [ createFakePlugin('postcss-plugin-2'), ...postCssOptions.plugins, ], }), webpackConfig, ); webpackConfig = applyConfigurePostCss( (postCssOptions) => ({ ...postCssOptions, plugins: [ ...postCssOptions.plugins, createFakePlugin('postcss-plugin-3'), ], }), webpackConfig, ); // @ts-expect-error: relax type const postCssLoader1 = webpackConfig.module?.rules[0].use[2]; expect(postCssLoader1.loader).toBe('postcss-loader-1'); const pluginNames1 = postCssLoader1.options.postcssOptions.plugins.map( (p: unknown[]) => p[0], ); expect(pluginNames1).toHaveLength(4); expect(pluginNames1).toEqual([ 'postcss-plugin-2', 'default-postcss-loader-1-plugin', 'postcss-plugin-1', 'postcss-plugin-3', ]); // @ts-expect-error: relax type const postCssLoader2 = webpackConfig.module?.rules[1].use[0]; expect(postCssLoader2.loader).toBe('postcss-loader-2'); const pluginNames2 = postCssLoader2.options.postcssOptions.plugins.map( (p: unknown[]) => p[0], ); expect(pluginNames2).toHaveLength(4); expect(pluginNames2).toEqual([ 'postcss-plugin-2', 'default-postcss-loader-2-plugin', 'postcss-plugin-1', 'postcss-plugin-3', ]); }); }); describe('getHttpsConfig', () => { const originalEnv = process.env; beforeEach(() => { jest.resetModules(); process.env = {...originalEnv}; }); afterAll(() => { process.env = originalEnv; }); it('returns true for HTTPS not env', async () => { await expect(getHttpsConfig()).resolves.toBe(false); }); it('returns true for HTTPS in env', async () => { process.env.HTTPS = 'true'; await expect(getHttpsConfig()).resolves.toBe(true); }); it('returns custom certs if they are in env', async () => { process.env.HTTPS = 'true'; process.env.SSL_CRT_FILE = path.join(__dirname, '__fixtures__/host.crt'); process.env.SSL_KEY_FILE = path.join(__dirname, '__fixtures__/host.key'); await expect(getHttpsConfig()).resolves.toEqual({ key: expect.any(Buffer), cert: expect.any(Buffer), }); }); it("throws if file doesn't exist", async () => { process.env.HTTPS = 'true'; process.env.SSL_CRT_FILE = path.join( __dirname, '__fixtures__/nonexistent.crt', ); process.env.SSL_KEY_FILE = path.join(__dirname, '__fixtures__/host.key'); await expect(getHttpsConfig()).rejects.toThrowErrorMatchingInlineSnapshot( `"You specified SSL_CRT_FILE in your env, but the file "<PROJECT_ROOT>/packages/docusaurus/src/webpack/__tests__/__fixtures__/nonexistent.crt" can't be found."`, ); }); it('throws for invalid key', async () => { process.env.HTTPS = 'true'; process.env.SSL_CRT_FILE = path.join(__dirname, '__fixtures__/host.crt'); process.env.SSL_KEY_FILE = path.join(__dirname, '__fixtures__/invalid.key'); await expect(getHttpsConfig()).rejects.toThrow(); }); it('throws for invalid cert', async () => { process.env.HTTPS = 'true'; process.env.SSL_CRT_FILE = path.join(__dirname, '__fixtures__/invalid.crt'); process.env.SSL_KEY_FILE = path.join(__dirname, '__fixtures__/host.key'); await expect(getHttpsConfig()).rejects.toThrow(); }); });
2,299
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/webpack/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/webpack/__tests__/__snapshots__/base.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`base webpack config creates webpack aliases 1`] = ` { "@docusaurus/BrowserOnly": "../../../../client/exports/BrowserOnly.tsx", "@docusaurus/ComponentCreator": "../../../../client/exports/ComponentCreator.tsx", "@docusaurus/ErrorBoundary": "../../../../client/exports/ErrorBoundary.tsx", "@docusaurus/ExecutionEnvironment": "../../../../client/exports/ExecutionEnvironment.ts", "@docusaurus/Head": "../../../../client/exports/Head.tsx", "@docusaurus/Interpolate": "../../../../client/exports/Interpolate.tsx", "@docusaurus/Link": "../../../../client/exports/Link.tsx", "@docusaurus/Noop": "../../../../client/exports/Noop.ts", "@docusaurus/Translate": "../../../../client/exports/Translate.tsx", "@docusaurus/constants": "../../../../client/exports/constants.ts", "@docusaurus/isInternalUrl": "../../../../client/exports/isInternalUrl.ts", "@docusaurus/renderRoutes": "../../../../client/exports/renderRoutes.ts", "@docusaurus/router": "../../../../client/exports/router.ts", "@docusaurus/useBaseUrl": "../../../../client/exports/useBaseUrl.ts", "@docusaurus/useDocusaurusContext": "../../../../client/exports/useDocusaurusContext.ts", "@docusaurus/useGlobalData": "../../../../client/exports/useGlobalData.ts", "@docusaurus/useIsBrowser": "../../../../client/exports/useIsBrowser.ts", "@docusaurus/useIsomorphicLayoutEffect": "../../../../client/exports/useIsomorphicLayoutEffect.tsx", "@docusaurus/useRouteContext": "../../../../client/exports/useRouteContext.tsx", "@generated": "../../../../../../..", "@site": "", "@theme-init/PluginThemeComponentEnhanced": "pluginThemeFolder/PluginThemeComponentEnhanced.js", "@theme-original/Error": "../../../../client/theme-fallback/Error/index.tsx", "@theme-original/Layout": "../../../../client/theme-fallback/Layout/index.tsx", "@theme-original/Loading": "../../../../client/theme-fallback/Loading/index.tsx", "@theme-original/NotFound": "../../../../client/theme-fallback/NotFound/index.tsx", "@theme-original/PluginThemeComponent1": "pluginThemeFolder/PluginThemeComponent1.js", "@theme-original/PluginThemeComponentEnhanced": "secondPluginThemeFolder/PluginThemeComponentEnhanced.js", "@theme-original/PluginThemeComponentOverriddenByUser": "pluginThemeFolder/PluginThemeComponentOverriddenByUser.js", "@theme-original/Root": "../../../../client/theme-fallback/Root/index.tsx", "@theme-original/SiteMetadata": "../../../../client/theme-fallback/SiteMetadata/index.tsx", "@theme-original/subfolder/PluginThemeComponent2": "pluginThemeFolder/subfolder/PluginThemeComponent2.js", "@theme/Error": "../../../../client/theme-fallback/Error/index.tsx", "@theme/Layout": "../../../../client/theme-fallback/Layout/index.tsx", "@theme/Loading": "../../../../client/theme-fallback/Loading/index.tsx", "@theme/NotFound": "../../../../client/theme-fallback/NotFound/index.tsx", "@theme/PluginThemeComponent1": "pluginThemeFolder/PluginThemeComponent1.js", "@theme/PluginThemeComponentEnhanced": "src/theme/PluginThemeComponentEnhanced.js", "@theme/PluginThemeComponentOverriddenByUser": "src/theme/PluginThemeComponentOverriddenByUser.js", "@theme/Root": "../../../../client/theme-fallback/Root/index.tsx", "@theme/SiteMetadata": "../../../../client/theme-fallback/SiteMetadata/index.tsx", "@theme/UserThemeComponent1": "src/theme/UserThemeComponent1.js", "@theme/subfolder/PluginThemeComponent2": "pluginThemeFolder/subfolder/PluginThemeComponent2.js", "@theme/subfolder/UserThemeComponent2": "src/theme/subfolder/UserThemeComponent2.js", } `;
2,301
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/webpack/aliases
petrpan-code/facebook/docusaurus/packages/docusaurus/src/webpack/aliases/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import fs from 'fs-extra'; import path from 'path'; import { loadThemeAliases, loadDocusaurusAliases, sortAliases, createAliasesForTheme, } from '../index'; import type {LoadedPlugin} from '@docusaurus/types'; describe('sortAliases', () => { // https://github.com/facebook/docusaurus/issues/6878 // Not sure if the risk actually happens, but still made tests to ensure that // behavior is consistent it('sorts reliably', () => { expect( Object.values( sortAliases({ '@a/b': 'b', '@a/b/c': 'c', '@a/b/c/d': 'd', }), ), ).toEqual(['d', 'c', 'b']); expect( Object.values( sortAliases({ '@a/b': 'b', '@a/b/c/d': 'd', '@a/b/c': 'c', }), ), ).toEqual(['d', 'c', 'b']); expect( Object.values( sortAliases({ '@a/b/c/d': 'd', '@a/b/c': 'c', '@a/b': 'b', }), ), ).toEqual(['d', 'c', 'b']); expect( Object.values( sortAliases({ '@a/b/c': 'c', '@a/b': 'b', '@a/b/c/d': 'd', }), ), ).toEqual(['d', 'c', 'b']); }); }); describe('createAliasesForTheme', () => { it('creates aliases for themePath 1 with components', async () => { const fixtures = path.join(__dirname, '__fixtures__'); const themePath = path.join(fixtures, 'theme-1'); const alias = await createAliasesForTheme(themePath, true); // Testing entries, because order matters! expect(Object.entries(alias)).toEqual( Object.entries({ '@theme-original/Footer': path.join(themePath, 'Footer/index.js'), '@theme-original/Layout': path.join(themePath, 'Layout.js'), '@theme/Footer': path.join(themePath, 'Footer/index.js'), '@theme/Layout': path.join(themePath, 'Layout.js'), }), ); expect(alias).not.toEqual({}); }); it('creates aliases for themePath 1 with components without original', async () => { const fixtures = path.join(__dirname, '__fixtures__'); const themePath = path.join(fixtures, 'theme-1'); const alias = await createAliasesForTheme(themePath, false); // Testing entries, because order matters! expect(Object.entries(alias)).toEqual( Object.entries({ '@theme/Footer': path.join(themePath, 'Footer/index.js'), '@theme/Layout': path.join(themePath, 'Layout.js'), }), ); expect(alias).not.toEqual({}); }); it('creates aliases for themePath 2 with components', async () => { const fixtures = path.join(__dirname, '__fixtures__'); const themePath = path.join(fixtures, 'theme-2'); const alias = await createAliasesForTheme(themePath, true); // Testing entries, because order matters! expect(Object.entries(alias)).toEqual( Object.entries({ '@theme-original/Layout': path.join(themePath, 'Layout/index.js'), '@theme-original/Navbar': path.join(themePath, 'Navbar.js'), '@theme-original/NavbarItem/NestedNavbarItem': path.join( themePath, 'NavbarItem/NestedNavbarItem/index.js', ), '@theme-original/NavbarItem/SiblingNavbarItem': path.join( themePath, 'NavbarItem/SiblingNavbarItem.js', ), '@theme-original/NavbarItem/zzz': path.join( themePath, 'NavbarItem/zzz.js', ), '@theme-original/NavbarItem': path.join( themePath, 'NavbarItem/index.js', ), '@theme/Layout': path.join(themePath, 'Layout/index.js'), '@theme/Navbar': path.join(themePath, 'Navbar.js'), '@theme/NavbarItem/NestedNavbarItem': path.join( themePath, 'NavbarItem/NestedNavbarItem/index.js', ), '@theme/NavbarItem/SiblingNavbarItem': path.join( themePath, 'NavbarItem/SiblingNavbarItem.js', ), '@theme/NavbarItem/zzz': path.join(themePath, 'NavbarItem/zzz.js'), '@theme/NavbarItem': path.join(themePath, 'NavbarItem/index.js'), }), ); expect(alias).not.toEqual({}); }); it('creates aliases for themePath 2 with components without original', async () => { const fixtures = path.join(__dirname, '__fixtures__'); const themePath = path.join(fixtures, 'theme-2'); const alias = await createAliasesForTheme(themePath, false); // Testing entries, because order matters! expect(Object.entries(alias)).toEqual( Object.entries({ '@theme/Layout': path.join(themePath, 'Layout/index.js'), '@theme/Navbar': path.join(themePath, 'Navbar.js'), '@theme/NavbarItem/NestedNavbarItem': path.join( themePath, 'NavbarItem/NestedNavbarItem/index.js', ), '@theme/NavbarItem/SiblingNavbarItem': path.join( themePath, 'NavbarItem/SiblingNavbarItem.js', ), '@theme/NavbarItem/zzz': path.join(themePath, 'NavbarItem/zzz.js'), '@theme/NavbarItem': path.join(themePath, 'NavbarItem/index.js'), }), ); expect(alias).not.toEqual({}); }); it('creates themePath with no components', async () => { const fixtures = path.join(__dirname, '__fixtures__'); const themePath = path.join(fixtures, 'empty-theme'); await fs.ensureDir(themePath); const alias = await createAliasesForTheme(themePath, true); expect(alias).toEqual({}); }); it('creates themePath with no components without original', async () => { const fixtures = path.join(__dirname, '__fixtures__'); const themePath = path.join(fixtures, 'empty-theme'); await fs.ensureDir(themePath); const alias = await createAliasesForTheme(themePath, false); expect(alias).toEqual({}); }); it('creates nothing for invalid themePath that does not exist', async () => { const fixtures = path.join(__dirname, '__fixtures__'); const themePath = path.join(fixtures, '__noExist__'); const alias = await createAliasesForTheme(themePath, true); expect(alias).toEqual({}); }); }); describe('getDocusaurusAliases', () => { it('returns appropriate webpack aliases', async () => { await expect(loadDocusaurusAliases()).resolves.toMatchSnapshot(); }); }); describe('loadThemeAliases', () => { it('next alias can override the previous alias', async () => { const fixtures = path.join(__dirname, '__fixtures__'); const theme1Path = path.join(fixtures, 'theme-1'); const theme2Path = path.join(fixtures, 'theme-2'); const alias = await loadThemeAliases({ siteDir: fixtures, plugins: [ {getThemePath: () => theme1Path}, {getThemePath: () => theme2Path}, ] as LoadedPlugin[], }); // Testing entries, because order matters! expect(Object.entries(alias)).toMatchSnapshot(); }); });
2,306
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/webpack/aliases/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/webpack/aliases/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`getDocusaurusAliases returns appropriate webpack aliases 1`] = ` { "@docusaurus/BrowserOnly": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/BrowserOnly.tsx", "@docusaurus/ComponentCreator": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/ComponentCreator.tsx", "@docusaurus/ErrorBoundary": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/ErrorBoundary.tsx", "@docusaurus/ExecutionEnvironment": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/ExecutionEnvironment.ts", "@docusaurus/Head": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/Head.tsx", "@docusaurus/Interpolate": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/Interpolate.tsx", "@docusaurus/Link": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/Link.tsx", "@docusaurus/Noop": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/Noop.ts", "@docusaurus/Translate": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/Translate.tsx", "@docusaurus/constants": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/constants.ts", "@docusaurus/isInternalUrl": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/isInternalUrl.ts", "@docusaurus/renderRoutes": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/renderRoutes.ts", "@docusaurus/router": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/router.ts", "@docusaurus/useBaseUrl": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/useBaseUrl.ts", "@docusaurus/useDocusaurusContext": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/useDocusaurusContext.ts", "@docusaurus/useGlobalData": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/useGlobalData.ts", "@docusaurus/useIsBrowser": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/useIsBrowser.ts", "@docusaurus/useIsomorphicLayoutEffect": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/useIsomorphicLayoutEffect.tsx", "@docusaurus/useRouteContext": "<PROJECT_ROOT>/packages/docusaurus/src/client/exports/useRouteContext.tsx", } `; exports[`loadThemeAliases next alias can override the previous alias 1`] = ` [ [ "@theme-init/Layout", "<PROJECT_ROOT>/packages/docusaurus/src/client/theme-fallback/Layout/index.tsx", ], [ "@theme-original/Error", "<PROJECT_ROOT>/packages/docusaurus/src/client/theme-fallback/Error/index.tsx", ], [ "@theme-original/Footer", "<PROJECT_ROOT>/packages/docusaurus/src/webpack/aliases/__tests__/__fixtures__/theme-1/Footer/index.js", ], [ "@theme-original/Layout", "<PROJECT_ROOT>/packages/docusaurus/src/webpack/aliases/__tests__/__fixtures__/theme-2/Layout/index.js", ], [ "@theme-original/Loading", "<PROJECT_ROOT>/packages/docusaurus/src/client/theme-fallback/Loading/index.tsx", ], [ "@theme-original/Navbar", "<PROJECT_ROOT>/packages/docusaurus/src/webpack/aliases/__tests__/__fixtures__/theme-2/Navbar.js", ], [ "@theme-original/NavbarItem/NestedNavbarItem", "<PROJECT_ROOT>/packages/docusaurus/src/webpack/aliases/__tests__/__fixtures__/theme-2/NavbarItem/NestedNavbarItem/index.js", ], [ "@theme-original/NavbarItem/SiblingNavbarItem", "<PROJECT_ROOT>/packages/docusaurus/src/webpack/aliases/__tests__/__fixtures__/theme-2/NavbarItem/SiblingNavbarItem.js", ], [ "@theme-original/NavbarItem/zzz", "<PROJECT_ROOT>/packages/docusaurus/src/webpack/aliases/__tests__/__fixtures__/theme-2/NavbarItem/zzz.js", ], [ "@theme-original/NavbarItem", "<PROJECT_ROOT>/packages/docusaurus/src/webpack/aliases/__tests__/__fixtures__/theme-2/NavbarItem/index.js", ], [ "@theme-original/NotFound", "<PROJECT_ROOT>/packages/docusaurus/src/client/theme-fallback/NotFound/index.tsx", ], [ "@theme-original/Root", "<PROJECT_ROOT>/packages/docusaurus/src/client/theme-fallback/Root/index.tsx", ], [ "@theme-original/SiteMetadata", "<PROJECT_ROOT>/packages/docusaurus/src/client/theme-fallback/SiteMetadata/index.tsx", ], [ "@theme/Error", "<PROJECT_ROOT>/packages/docusaurus/src/client/theme-fallback/Error/index.tsx", ], [ "@theme/Footer", "<PROJECT_ROOT>/packages/docusaurus/src/webpack/aliases/__tests__/__fixtures__/theme-1/Footer/index.js", ], [ "@theme/Layout", "<PROJECT_ROOT>/packages/docusaurus/src/webpack/aliases/__tests__/__fixtures__/theme-2/Layout/index.js", ], [ "@theme/Loading", "<PROJECT_ROOT>/packages/docusaurus/src/client/theme-fallback/Loading/index.tsx", ], [ "@theme/Navbar", "<PROJECT_ROOT>/packages/docusaurus/src/webpack/aliases/__tests__/__fixtures__/theme-2/Navbar.js", ], [ "@theme/NavbarItem/NestedNavbarItem", "<PROJECT_ROOT>/packages/docusaurus/src/webpack/aliases/__tests__/__fixtures__/theme-2/NavbarItem/NestedNavbarItem/index.js", ], [ "@theme/NavbarItem/SiblingNavbarItem", "<PROJECT_ROOT>/packages/docusaurus/src/webpack/aliases/__tests__/__fixtures__/theme-2/NavbarItem/SiblingNavbarItem.js", ], [ "@theme/NavbarItem/zzz", "<PROJECT_ROOT>/packages/docusaurus/src/webpack/aliases/__tests__/__fixtures__/theme-2/NavbarItem/zzz.js", ], [ "@theme/NavbarItem", "<PROJECT_ROOT>/packages/docusaurus/src/webpack/aliases/__tests__/__fixtures__/theme-2/NavbarItem/index.js", ], [ "@theme/NotFound", "<PROJECT_ROOT>/packages/docusaurus/src/client/theme-fallback/NotFound/index.tsx", ], [ "@theme/Root", "<PROJECT_ROOT>/packages/docusaurus/src/client/theme-fallback/Root/index.tsx", ], [ "@theme/SiteMetadata", "<PROJECT_ROOT>/packages/docusaurus/src/client/theme-fallback/SiteMetadata/index.tsx", ], ] `;
2,323
0
petrpan-code/facebook/docusaurus/packages/eslint-plugin/src/rules
petrpan-code/facebook/docusaurus/packages/eslint-plugin/src/rules/__tests__/no-html-links.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import rule from '../no-html-links'; import {RuleTester} from './testUtils'; const errorsJSX = [{messageId: 'link'}] as const; const ruleTester = new RuleTester({ parser: '@typescript-eslint/parser', parserOptions: { ecmaFeatures: { jsx: true, }, }, }); ruleTester.run('prefer-docusaurus-link', rule, { valid: [ { code: '<Link to="/test">test</Link>', }, { code: '<Link to="https://twitter.com/docusaurus">Twitter</Link>', }, { code: '<a href="https://twitter.com/docusaurus">Twitter</a>', options: [{ignoreFullyResolved: true}], }, { code: '<a href={`https://twitter.com/docusaurus`}>Twitter</a>', options: [{ignoreFullyResolved: true}], }, { code: '<a href="mailto:[email protected]">Contact</a> ', options: [{ignoreFullyResolved: true}], }, { code: '<a href="tel:123456789">Call</a>', options: [{ignoreFullyResolved: true}], }, ], invalid: [ { code: '<a href="/test">test</a>', errors: errorsJSX, }, { code: '<a href="https://twitter.com/docusaurus" target="_blank">test</a>', errors: errorsJSX, }, { code: '<a href="https://twitter.com/docusaurus" target="_blank" rel="noopener noreferrer">test</a>', errors: errorsJSX, }, { code: '<a href="mailto:[email protected]">Contact</a> ', errors: errorsJSX, }, { code: '<a href="tel:123456789">Call</a>', errors: errorsJSX, }, { code: '<a href={``}>Twitter</a>', errors: errorsJSX, }, { code: '<a href={`https://www.twitter.com/docusaurus`}>Twitter</a>', errors: errorsJSX, }, { code: '<a href="www.twitter.com/docusaurus">Twitter</a>', options: [{ignoreFullyResolved: true}], errors: errorsJSX, }, { // TODO we might want to make this test pass // Can template literals be statically pre-evaluated? (Babel can do it) // eslint-disable-next-line no-template-curly-in-string code: '<a href={`https://twitter.com/${"docu" + "saurus"} ${"rex"}`}>Twitter</a>', options: [{ignoreFullyResolved: true}], errors: errorsJSX, }, ], });
2,324
0
petrpan-code/facebook/docusaurus/packages/eslint-plugin/src/rules
petrpan-code/facebook/docusaurus/packages/eslint-plugin/src/rules/__tests__/no-untranslated-text.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import rule from '../no-untranslated-text'; import {getCommonValidTests, RuleTester} from './testUtils'; const errorsJSX = [{messageId: 'translateChildren'}] as const; const ruleTester = new RuleTester({ parser: '@typescript-eslint/parser', parserOptions: { ecmaFeatures: { jsx: true, }, }, }); ruleTester.run('no-untranslated-text', rule, { valid: [ ...getCommonValidTests(), { code: '<Component>·</Component>', options: [{ignoredStrings: ['·', '—', '×']}], }, { code: '<Component>· </Component>', options: [{ignoredStrings: ['·', '—', '×']}], }, { code: '<Component> · </Component>', options: [{ignoredStrings: ['·', '—', '×']}], }, { code: '<Component>· ·</Component>', options: [{ignoredStrings: ['·', '—', '×']}], }, { code: '<Component>· — ×</Component>', options: [{ignoredStrings: ['·', '—', '×']}], }, { code: '<Component>{"·"}</Component>', options: [{ignoredStrings: ['·']}], }, { code: "<Component>{'·'}</Component>", options: [{ignoredStrings: ['·']}], }, { code: '<Component>{`·`}</Component>', options: [{ignoredStrings: ['·', '—', '×']}], }, { code: '<Component>Docusaurus</Component>', options: [{ignoredStrings: ['Docusaurus']}], }, { code: '<Component>&#8203;</Component>', options: [{ignoredStrings: ['​']}], }, { code: `<> {' · '} </>`, options: [{ignoredStrings: ['·']}], }, ], invalid: [ { code: '<Component>text</Component>', errors: errorsJSX, }, { code: '<Component> text </Component>', errors: errorsJSX, }, { code: '<Component>"text"</Component>', errors: errorsJSX, }, { code: "<Component>'text'</Component>", errors: errorsJSX, }, { code: '<Component>`text`</Component>', errors: errorsJSX, }, { code: '<Component>{"text"}</Component>', errors: errorsJSX, }, { code: "<Component>{'text'}</Component>", errors: errorsJSX, }, { code: '<Component>{`text`}</Component>', errors: errorsJSX, }, { code: '<>text</>', errors: errorsJSX, }, { code: '<Component>· — ×</Component>', errors: errorsJSX, options: [{ignoredStrings: ['·', '—']}], }, { code: '<Component>··</Component>', errors: errorsJSX, options: [{ignoredStrings: ['·', '—', '×']}], }, { code: '<Component> ·· </Component>', errors: errorsJSX, options: [{ignoredStrings: ['·', '—', '×']}], }, { code: '<Component>"·"</Component>', errors: errorsJSX, options: [{ignoredStrings: ['·', '—', '×']}], }, { code: "<Component>'·'</Component>", errors: errorsJSX, options: [{ignoredStrings: ['·', '—', '×']}], }, { code: '<Component>`·`</Component>', errors: errorsJSX, options: [{ignoredStrings: ['·', '—', '×']}], }, { code: '<Component>Docusaurus</Component>', errors: errorsJSX, options: [{ignoredStrings: ['Docu', 'saurus']}], }, ], });
2,325
0
petrpan-code/facebook/docusaurus/packages/eslint-plugin/src/rules
petrpan-code/facebook/docusaurus/packages/eslint-plugin/src/rules/__tests__/prefer-docusaurus-heading.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import rule from '../prefer-docusaurus-heading'; import {RuleTester} from './testUtils'; const errorsJSX = [{messageId: 'headings'}] as const; const ruleTester = new RuleTester({ parser: '@typescript-eslint/parser', parserOptions: { ecmaFeatures: { jsx: true, }, }, }); ruleTester.run('prefer-docusaurus-heading', rule, { valid: [ { code: "<Heading as='h1'>heading 1</Heading>", }, { code: "<Heading as='h2'>heading 2</Heading>", }, { code: "<Heading as='h3'>heading 3</Heading>", }, { code: "<Heading as='h4'>heading 4</Heading>", }, { code: "<Heading as='h5'>heading 5</Heading>", }, { code: "<Heading as='h6'>heading 6</Heading>", }, ], invalid: [ { code: '<h1>heading 1</h1>', errors: errorsJSX, }, { code: '<h2>heading 2</h2>', errors: errorsJSX, }, { code: '<h3>heading 3</h3>', errors: errorsJSX, }, { code: '<h4>heading 4</h4>', errors: errorsJSX, }, { code: '<h5>heading 5</h5>', errors: errorsJSX, }, { code: '<h6>heading 6</h6>', errors: errorsJSX, }, ], });
2,326
0
petrpan-code/facebook/docusaurus/packages/eslint-plugin/src/rules
petrpan-code/facebook/docusaurus/packages/eslint-plugin/src/rules/__tests__/string-literal-i18n-messages.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import rule from '../string-literal-i18n-messages'; import {getCommonValidTests, RuleTester} from './testUtils'; const errorsJSX = [{messageId: 'translateChildren'}] as const; const errorsFunc = [{messageId: 'translateArg'}] as const; const ruleTester = new RuleTester({ parser: '@typescript-eslint/parser', parserOptions: { ecmaFeatures: { jsx: true, }, }, }); ruleTester.run('string-literal-i18n-messages', rule, { valid: [...getCommonValidTests()], invalid: [ { code: '<Translate>{text}</Translate>', errors: errorsJSX, }, { code: '<Translate>Hi {text} my friend</Translate>', errors: errorsJSX, }, { code: '<Translate> {text} </Translate>', errors: errorsJSX, }, { code: '<Translate>`{text}`</Translate>', errors: errorsJSX, }, { // eslint-disable-next-line no-template-curly-in-string code: '<Translate>{`${text}`}</Translate>', errors: errorsJSX, }, { code: 'translate({message: metaTitle})', errors: errorsFunc, }, ], });
2,334
0
petrpan-code/facebook/docusaurus/packages/lqip-loader/src
petrpan-code/facebook/docusaurus/packages/lqip-loader/src/__tests__/lqip.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import {base64} from '../lqip'; const imgPath = path.join(__dirname, '__fixtures__', 'endi.jpg'); const invalidPath = path.join(__dirname, '__fixtures__', 'docusaurus.svg'); describe('base64', () => { it('rejects unknown or unsupported file format', async () => { await expect(base64(invalidPath)).rejects.toThrow( /Error: Input file is missing or uses unsupported image format, lqip v.*/, ); }); it('generates a valid base64', async () => { const expectedBase64 = 'data:image/jpeg;base64,/9j/2wBDA'; await expect(base64(imgPath)).resolves.toContain(expectedBase64); }); });
2,340
0
petrpan-code/facebook/docusaurus/packages/stylelint-copyright/src
petrpan-code/facebook/docusaurus/packages/stylelint-copyright/src/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable jest/no-conditional-expect */ import path from 'path'; import stylelint from 'stylelint'; import rule from '../index'; declare global { namespace jest { interface Matchers<R> { toHaveMessage: () => R; } } } type TestSuite = { ruleName: string; fix: boolean; accept: TestCase[]; reject: TestCase[]; }; type TestCase = { code: string; description?: string; fixed?: string; message?: string; line?: number; column?: number; }; function getOutputCss(output: stylelint.LinterResult) { // eslint-disable-next-line no-underscore-dangle const result = output.results[0]!._postcssResult!; return result.root.toString(result.opts!.syntax); } function testStylelintRule(config: stylelint.Config, tests: TestSuite) { describe(`${tests.ruleName}`, () => { const checkTestCaseContent = (testCase: TestCase) => testCase.description ?? testCase.code; describe('accept cases', () => { tests.accept.forEach((testCase) => { it(`${checkTestCaseContent(testCase)}`, async () => { const options: stylelint.LinterOptions = { code: testCase.code, config, }; const output = await stylelint.lint(options); expect(output.results[0]!.warnings).toEqual([]); if (!tests.fix) { return; } const fixedOutput = await stylelint.lint({...options, fix: true}); const fixedCode = getOutputCss(fixedOutput); expect(fixedCode).toBe(testCase.code); }); }); }); describe('reject cases', () => { tests.reject.forEach((testCase) => { it(`${checkTestCaseContent(testCase)}`, async () => { const options = { code: testCase.code, config, }; const output = await stylelint.lint(options); const {warnings} = output.results[0]!; const warning = warnings[0]!; expect(warnings.length).toBeGreaterThanOrEqual(1); expect(testCase).toHaveMessage(); if (testCase.message != null) { expect(warning.text).toBe(testCase.message); } if (testCase.line != null) { expect(warning.line).toBe(testCase.line); } if (testCase.column != null) { expect(warning.column).toBe(testCase.column); } if (!tests.fix) { return; } if (!testCase.fixed) { throw new Error( 'If using { fix: true } in test tests, all reject cases must have { fixed: .. }', ); } const fixedOutput = await stylelint.lint({...options, fix: true}); const fixedCode = getOutputCss(fixedOutput); expect(fixedCode).toBe(testCase.fixed); }); }); }); expect.extend({ toHaveMessage(testCase: TestCase) { if (testCase.message == null) { return { message: () => 'Expected "reject" test case to have a "message" property', pass: false, }; } return { message: () => 'Expected "reject" test case to not have a "message" property', pass: true, }; }, }); }); } testStylelintRule( { plugins: [path.join(__dirname, '../../lib/index.js')], rules: { [rule.ruleName]: [true, {header: '*\n * Copyright'}], }, }, { ruleName: rule.ruleName, fix: true, accept: [ { code: ` /** * Copyright */ .foo {}`, }, { code: `/** * Copyright */ .foo {}`, }, { code: `/** * Copyright */ .foo {}`, }, ], reject: [ { code: `.foo {}`, fixed: `/** * Copyright */ .foo {}`, message: 'Missing copyright in the header comment (docusaurus/copyright-header)', line: 1, column: 1, }, { code: ` .foo {}`, fixed: `/** * Copyright */ .foo {}`, message: 'Missing copyright in the header comment (docusaurus/copyright-header)', line: 1, column: 1, }, { code: `/** * Copyright */ .foo {}`, fixed: `/** * Copyright */ /** * Copyright */ .foo {}`, message: 'Missing copyright in the header comment (docusaurus/copyright-header)', line: 1, column: 1, }, { code: `/** * Copyleft */ .foo {}`, fixed: `/** * Copyright */ /** * Copyleft */ .foo {}`, message: 'Missing copyright in the header comment (docusaurus/copyright-header)', line: 1, column: 1, }, { code: `/** * Copyleft */ /** * Copyright */ .foo {}`, fixed: `/** * Copyright */ /** * Copyleft */ /** * Copyright */ .foo {}`, message: 'Missing copyright in the header comment (docusaurus/copyright-header)', line: 1, column: 1, }, ], }, );
2,631
0
petrpan-code/facebook/docusaurus/website/src/data
petrpan-code/facebook/docusaurus/website/src/data/__tests__/user.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import fs from 'fs-extra'; import path from 'path'; import _ from 'lodash'; import imageSize from 'image-size'; import {Joi} from '@docusaurus/utils-validation'; import {TagList, sortedUsers, type User} from '../users'; declare global { namespace jest { interface Matchers<R> { toHaveGoodDimensions: () => R; } } } expect.extend({ toHaveGoodDimensions({width, height}: {width: number; height: number}) { // Put this one first because aspect ratio is harder to fix than resizing // (need to take another screenshot) if (width / height > 2) { return { pass: false, message: () => `The preview image's width is ${width} and height is ${height}. To make sure it takes up the entire container in our showcase card, it needs to have an aspect ratio of no wider than 2:1. Please make your image taller.`, }; } else if (width < 640) { return { pass: false, message: () => `The preview image's width is ${width}, but we require a minimum 640. You can either resize it locally, or you can wait for the maintainer to resize it for you.`, }; } return { pass: true, message: () => "The preview image's dimensions are good", }; }, }); describe('users data', () => { it.each(sortedUsers)('$title', (user) => { Joi.attempt( user, Joi.object<User>({ title: Joi.string().required(), description: Joi.string() .required() .max(120) .message( 'Please constrain your description text to maximum 120 characters.', ), website: Joi.string() .pattern(/^https?:\/\//) .message('') .required(), // The preview should be jest/emptyModule preview: Joi.object({default: Joi.any()}) .unknown(false) .allow(null) .required() .messages({ 'object.base': 'The image should be hosted on Docusaurus site, and not use remote HTTP or HTTPS URLs. It must be imported with require().', }), tags: Joi.array() .items(...TagList) .required(), source: Joi.string().allow(null).required().messages({ 'any.required': "The source attribute is required.\nIf your Docusaurus site is not open-source, please make it explicit with 'source: null'.", }), }).unknown(false), ); // cSpell:ignore opensource if (user.tags.includes('opensource') && user.source === null) { throw new Error( "You can't add the 'opensource' tag to a site that does not have a link to source code. Please add your source code, or remove this tag.", ); } else if (user.source !== null && !user.tags.includes('opensource')) { throw new Error( "For open-source sites, please add the 'opensource' tag.", ); } }); it('does not contain duplicates', () => { function normalizeUrl(url: string | null) { if (url === null) { return null; } if (!url.endsWith('/')) { return `${url}/`; } return url; } function duplicatesBy(mapper: (user: User) => string | null) { const grouped: {[key: string]: User[]} = _.groupBy(sortedUsers, (user) => mapper(user), ); return Object.fromEntries( Object.entries(grouped).filter((entry) => entry[1].length > 1), ); } let duplicatesLog = ''; const duplicatesByTitle = duplicatesBy((user) => user.title.trim().toLowerCase(), ); Object.entries(duplicatesByTitle).forEach(([title, users]) => { duplicatesLog += `Showcase site title '${title}' is used ${users.length} times! Duplicates are not allowed!\n`; }); const duplicatesByDescription = duplicatesBy((user) => user.description.trim().toLowerCase(), ); Object.entries(duplicatesByDescription).forEach(([description, users]) => { duplicatesLog += `Showcase site description '${description}' is used ${users.length} times! Duplicates are not allowed!\n`; }); const duplicatesByWebsite = duplicatesBy((user) => normalizeUrl(user.website), ); Object.entries(duplicatesByWebsite).forEach(([website, users]) => { duplicatesLog += `Showcase site website url '${website}' is used ${users.length} times! Duplicates are not allowed!\n`; }); const duplicatesBySource = duplicatesBy((user) => normalizeUrl(user.source), ); Object.entries(duplicatesBySource).forEach(([source, users]) => { // source is allowed to be null for multiple sites // "null", see Lodash groupBy issue: https://github.com/lodash/lodash/issues/3060 if (source && source !== 'null') { duplicatesLog += `Showcase site source url '${source}' is used ${users.length} times! Duplicates are not allowed!\n`; } }); if (duplicatesLog) { throw new Error(duplicatesLog); } }); }); describe('preview images', () => { const imageDir = path.join(__dirname, '../showcase'); // eslint-disable-next-line no-restricted-properties const files = fs .readdirSync(imageDir) .filter((file) => ['.png', 'jpg', '.jpeg'].includes(path.extname(file))); it.each(files)('%s', (file) => { const size = imageSize(path.join(imageDir, file)); expect(size).toHaveGoodDimensions(); }); });
2,687
0
petrpan-code/facebook/docusaurus/website/src/utils
petrpan-code/facebook/docusaurus/website/src/utils/__tests__/jsUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {toggleListItem} from '../jsUtils'; describe('toggleListItem', () => { it('removes item already in list', () => { expect(toggleListItem([1, 2, 3], 2)).toEqual([1, 3]); }); it('appends item not in list', () => { expect(toggleListItem([1, 2], 3)).toEqual([1, 2, 3]); }); });
3,022
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/constructors
petrpan-code/styled-components/styled-components/packages/styled-components/src/constructors/test/createGlobalStyle.ssr.test.tsx
/** * @jest-environment node */ import React from 'react'; import ReactDOMServer from 'react-dom/server'; import ServerStyleSheet from '../../models/ServerStyleSheet'; import { stripComments, stripWhitespace } from '../../test/utils'; import createGlobalStyle from '../createGlobalStyle'; describe(`createGlobalStyle`, () => { let context: ReturnType<typeof setup>; function setup() { return { renderToString(comp: JSX.Element) { return ReactDOMServer.renderToString(comp); }, }; } beforeEach(() => { context = setup(); }); it(`injects global <style> when rendered to string`, () => { const sheet = new ServerStyleSheet(); const Component = createGlobalStyle`[data-test-inject]{color:red;} `; const html = context.renderToString(sheet.collectStyles(<Component />)); const styles = stripOuterHTML(sheet.getStyleTags()); expect(html).toBe(''); expect(stripWhitespace(stripComments(styles))).toMatchInlineSnapshot( `"[data-test-inject]{ color:red; } data-styled.g1[id="sc-global-a1"]{ content:"sc-global-a1,"} "` ); }); }); function stripOuterHTML(html: string) { return html.replace(/<[^>]*>([^<]*)<[^>]*>/g, '$1'); }
3,023
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/constructors
petrpan-code/styled-components/styled-components/packages/styled-components/src/constructors/test/createGlobalStyle.test.tsx
import React from 'react'; import ReactDOM from 'react-dom'; import { act, Simulate } from 'react-dom/test-utils'; import ReactTestRenderer from 'react-test-renderer'; import * as constants from '../../constants'; import { StyleSheetManager } from '../../models/StyleSheetManager'; import ThemeProvider from '../../models/ThemeProvider'; import StyleSheet from '../../sheet'; import { getRenderedCSS, resetStyled } from '../../test/utils'; import createGlobalStyle from '../createGlobalStyle'; import keyframes from '../keyframes'; describe(`createGlobalStyle`, () => { let context: ReturnType<typeof setup>; function setup() { const container = document.createElement('div'); document.body.appendChild(container); return { container, render(comp: JSX.Element) { ReactDOM.render(comp, container); }, cleanup() { resetStyled(); document.body.removeChild(container); }, }; } beforeEach(() => { context = setup(); }); afterEach(() => { context.cleanup(); }); it(`injects global <style> when rendered`, () => { const { render } = context; const Component = createGlobalStyle`[data-test-inject]{color:red;} `; render(<Component />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "[data-test-inject] { color: red; }" `); }); it(`supports interpolation`, () => { const { render } = context; const Component = createGlobalStyle<{ color: string }>`div {color:${props => props.color};} `; render(<Component color="orange" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "div { color: orange; }" `); }); it(`supports objects with a function`, () => { const { render } = setup(); const Component = createGlobalStyle({ 'h1, h2, h3, h4, h5, h6': { fontFamily: ({ theme }) => theme.fonts.heading, }, }); render(<Component theme={{ fonts: { heading: 'sans-serif' } }} />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "h1, h2, h3, h4, h5, h6 { font-family: sans-serif; }" `); }); it(`supports nested objects with a function`, () => { const { render } = setup(); const Component1 = createGlobalStyle({ 'div, span': { h1: { span: { fontFamily: ({ theme }) => theme.fonts.heading, }, }, }, }); render(<Component1 theme={{ fonts: { heading: 'sans-serif' } }} />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "div h1 span, span h1 span { font-family: sans-serif; }" `); }); it(`supports theming`, () => { const { render } = context; const Component = createGlobalStyle`div {color:${props => props.theme.color};} `; render( <ThemeProvider theme={{ color: 'black' }}> <Component /> </ThemeProvider> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` "div { color: black; }" `); }); it(`updates theme correctly`, () => { const { render } = context; const Component = createGlobalStyle`div {color:${props => props.theme.color};} `; let update: any; class App extends React.Component { state = { color: 'grey' }; constructor(props: {}) { super(props); update = (payload: {}) => { this.setState(payload); }; } render() { return ( <ThemeProvider theme={{ color: this.state.color }}> <Component /> </ThemeProvider> ); } } render(<App />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "div { color: grey; }" `); update({ color: 'red' }); expect(getRenderedCSS()).toMatchInlineSnapshot(` "div { color: red; }" `); }); it('should work in StrictMode without warnings', () => { const { render } = context; const spy = jest.spyOn(console, 'error').mockImplementation(() => {}); const Comp = createGlobalStyle` html { color: red; } `; act(() => { render( <React.StrictMode> <Comp /> </React.StrictMode> ); }); expect(spy).not.toHaveBeenCalled(); }); it('should not inject twice in StrictMode', () => { jest.spyOn(StyleSheet, 'registerId'); const { render } = context; const spy = jest.spyOn(console, 'error').mockImplementation(() => {}); const Comp = createGlobalStyle` html { color: red; } `; act(() => { render( <React.StrictMode> <Comp /> </React.StrictMode> ); }); expect(spy).not.toHaveBeenCalled(); expect(StyleSheet.registerId).toHaveBeenCalledTimes(1); }); it(`renders to StyleSheetManager.target`, () => { const { container, render } = context; const Component = createGlobalStyle`[data-test-target]{color:red;} `; render( <StyleSheetManager target={container}> <Component /> </StyleSheetManager> ); const style = container.firstElementChild!; expect(style.tagName).toBe('STYLE'); expect(style.textContent).toContain(`[data-test-target]{color:red;}`); }); it(`adds new global rules non-destructively`, () => { const { render } = context; const Color = createGlobalStyle`[data-test-add]{color:red;} `; const Background = createGlobalStyle`[data-test-add]{background:yellow;} `; render( <React.Fragment> <Color /> <Background /> </React.Fragment> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` "[data-test-add] { color: red; } [data-test-add] { background: yellow; }" `); }); it(`stringifies multiple rules correctly`, () => { const { render } = context; const Component = createGlobalStyle<{ fg: any; bg: any }>` div { color: ${props => props.fg}; background: ${props => props.bg}; } `; render(<Component fg="red" bg="green" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "div { color: red; background: green; }" `); }); it(`injects multiple <GlobalStyle> components correctly`, () => { const { render } = context; const A = createGlobalStyle`body { background: palevioletred; }`; const B = createGlobalStyle`body { color: white; }`; render( <React.Fragment> <A /> <B /> </React.Fragment> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` "body { background: palevioletred; } body { color: white; }" `); }); it(`removes styling injected styling when unmounted`, () => { const ComponentA = createGlobalStyle`[data-test-remove]{color:grey;} `; const ComponentB = createGlobalStyle`[data-test-keep]{color:blue;} `; class Comp extends React.Component<{ insert: boolean }> { render() { return this.props.insert ? <ComponentA /> : <ComponentB />; } } const renderer = ReactTestRenderer.create(<Comp insert />); ReactTestRenderer.act(() => { expect(getRenderedCSS()).toMatchInlineSnapshot(` "[data-test-remove] { color: grey; }" `); renderer.update(<Comp insert={false} />); }); ReactTestRenderer.act(() => { expect(getRenderedCSS()).toMatchInlineSnapshot(` "[data-test-keep] { color: blue; }" `); }); }); it(`removes styling injected for multiple <GlobalStyle> components correctly`, () => { const { render } = context; const A = createGlobalStyle`body { background: palevioletred; }`; const B = createGlobalStyle`body { color: white; }`; class Comp extends React.Component { state = { a: true, b: true, }; onClick() { if (this.state.a === true && this.state.b === true) { this.setState({ a: true, b: false, }); } else if (this.state.a === true && this.state.b === false) { this.setState({ a: false, b: false, }); } else { this.setState({ a: true, b: true, }); } } render() { return ( <div data-test-el onClick={() => this.onClick()}> {this.state.a ? <A /> : null} {this.state.b ? <B /> : null} </div> ); } } render(<Comp />); const el = document.querySelector('[data-test-el]')!; expect(getRenderedCSS()).toMatchInlineSnapshot(` "body { background: palevioletred; } body { color: white; }" `); // should have both styles Simulate.click(el); expect(getRenderedCSS()).toMatchInlineSnapshot(` "body { background: palevioletred; }" `); // should only have palevioletred Simulate.click(el); expect(getRenderedCSS()).toMatchInlineSnapshot(`""`); // should be empty }); it(`removes styling injected for multiple instances of same <GlobalStyle> components correctly`, () => { jest.spyOn(console, 'warn').mockImplementation(() => {}); const { render } = context; const A = createGlobalStyle<{ bgColor?: any }>` body { background: ${props => props.bgColor}; } `; render(<A bgColor="blue" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "body { background: blue; }" `); render(<A bgColor="red" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "body { background: red; }" `); render(<A />); expect(getRenderedCSS()).toMatchInlineSnapshot(`""`); }); it(`should warn when children are passed as props`, () => { jest.spyOn(console, 'warn').mockImplementation(() => {}); const { render } = context; const Component = createGlobalStyle<{ fg: any; bg: any }>` div { color: ${props => props.fg}; background: ${props => props.bg}; } `; render( // @ts-expect-error children not expected <Component fg="red" bg="green"> <div /> </Component> ); const warn = console.warn as jest.Mock<Console['warn']>; expect(warn.mock.calls[0][0]).toMatchInlineSnapshot( `"The global style component sc-global-a was given child JSX. createGlobalStyle does not render children."` ); }); it(`should warn when @import is used`, () => { jest.spyOn(console, 'warn').mockImplementation(() => {}); const { render } = context; const Component = createGlobalStyle` @import url("something.css"); `; render(<Component />); const warn = console.warn as jest.Mock<Console['warn']>; expect(warn.mock.calls[0][0]).toMatchInlineSnapshot( `"Please do not use @import CSS syntax in createGlobalStyle at this time, as the CSSOM APIs we use in production do not handle it well. Instead, we recommend using a library such as react-helmet to inject a typical <link> meta tag to the stylesheet, or simply embedding it manually in your index.html <head> section for a simpler app."` ); }); it('works with keyframes', () => { const { render } = context; const rotate360 = keyframes` from { transform: rotate(0deg); } to { transform: rotate(360deg); } `; const GlobalStyle = createGlobalStyle` div { display: inline-block; animation: ${rotate360} 2s linear infinite; padding: 2rem 1rem; font-size: 1.2rem; } `; render( <div> <GlobalStyle /> <div>&lt; 💅 &gt;</div> </div> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` "div { display: inline-block; animation: a 2s linear infinite; padding: 2rem 1rem; font-size: 1.2rem; } @keyframes a { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }" `); }); it(`removes style tag in StyleSheetManager.target when unmounted after target detached and no other global styles`, () => { // Set DISABLE_SPEEDY flag to false to force using speedy tag const flag = constants.DISABLE_SPEEDY; // @ts-expect-error it's ok constants.DISABLE_SPEEDY = false; const container = document.createElement('div'); document.body.appendChild(container); const styleContainer = document.createElement('div'); document.body.appendChild(styleContainer); const Component = createGlobalStyle`[data-test-unmount-remove]{color:grey;} `; class Comp extends React.Component { render() { return ( <div> <StyleSheetManager target={styleContainer}> <Component /> </StyleSheetManager> </div> ); } } ReactDOM.render(<Comp />, container); // Check styles const style = styleContainer.firstElementChild as HTMLStyleElement; expect((style!.sheet!.cssRules[0] as CSSStyleRule).selectorText).toBe( '[data-test-unmount-remove]' ); // detach container and unmount react component try { document.body.removeChild(container); document.body.removeChild(styleContainer); ReactDOM.unmountComponentAtNode(container); } catch (e) { fail('should not throw exception'); } // Reset DISABLE_SPEEDY flag // @ts-expect-error it's ok constants.DISABLE_SPEEDY = flag; }); it(`injects multiple global styles in definition order, not composition order`, () => { const { render } = context; const GlobalStyleOne = createGlobalStyle`[data-test-inject]{color:red;} `; const GlobalStyleTwo = createGlobalStyle`[data-test-inject]{color:green;} `; render( <> <GlobalStyleTwo /> <GlobalStyleOne /> </> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` "[data-test-inject] { color: red; } [data-test-inject] { color: green; }" `); }); });
3,024
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/constructors
petrpan-code/styled-components/styled-components/packages/styled-components/src/constructors/test/keyframes.test.tsx
import React from 'react'; import TestRenderer from 'react-test-renderer'; import stylisRTLPlugin from 'stylis-plugin-rtl'; import Keyframes from '../../models/Keyframes'; import { StyleSheetManager } from '../../models/StyleSheetManager'; import { getRenderedCSS, resetStyled } from '../../test/utils'; import css from '../css'; import keyframes from '../keyframes'; // Disable isStaticRules optimisation since we're not // testing for ComponentStyle specifics here jest.mock('../../utils/isStaticRules', () => () => false); let styled: ReturnType<typeof resetStyled>; describe('keyframes', () => { beforeEach(() => { styled = resetStyled(); }); it('should return Keyframes instance', () => { expect(keyframes` 0% { opacity: 0; } 100% { opacity: 1; } `).toBeInstanceOf(Keyframes); }); it('should return its name via .getName()', () => { expect( keyframes` 0% { opacity: 0; } 100% { opacity: 1; } `.getName() ).toMatchInlineSnapshot(`"a"`); }); it('should insert the correct styles', () => { const rules = ` 0% { opacity: 0; } 100% { opacity: 1; } `; const animation = keyframes`${rules}`; expect(getRenderedCSS()).toMatchInlineSnapshot(`""`); const Comp = styled.div` animation: ${animation} 2s linear infinite; `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".c { animation: a 2s linear infinite; } @keyframes a { 0% { opacity: 0; } 100% { opacity: 1; } }" `); }); it('should insert the correct styles for objects', () => { const rules = ` 0% { opacity: 0; } 100% { opacity: 1; } `; const animation = keyframes`${rules}`; expect(getRenderedCSS()).toMatchInlineSnapshot(`""`); const Comp = styled.div({ animation: css` ${animation} 2s linear infinite `, }); TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".c { animation: a 2s linear infinite; } @keyframes a { 0% { opacity: 0; } 100% { opacity: 1; } }" `); }); it('should insert the correct styles for objects with nesting', () => { const rules = ` 0% { opacity: 0; } 100% { opacity: 1; } `; const animation = keyframes`${rules}`; expect(getRenderedCSS()).toMatchInlineSnapshot(`""`); const Comp = styled.div({ '@media(max-width: 700px)': { animation: css` ${animation} 2s linear infinite `, ':hover': { animation: css` ${animation} 10s linear infinite `, }, }, }); TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "@media(max-width:700px) { .c { animation: a 2s linear infinite; } .c :hover { animation: a 10s linear infinite; } } @keyframes a { 0% { opacity: 0; } 100% { opacity: 1; } }" `); }); it('should insert the correct styles when keyframes in props', () => { const rules = ` 0% { opacity: 0; } 100% { opacity: 1; } `; const animation = keyframes`${rules}`; expect(getRenderedCSS()).toMatchInlineSnapshot(`""`); const Comp = styled.div<{ animation: any }>` animation: ${props => props.animation} 2s linear infinite; `; TestRenderer.create(<Comp animation={animation} />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".c { animation: a 2s linear infinite; } @keyframes a { 0% { opacity: 0; } 100% { opacity: 1; } }" `); }); it('should handle interpolations', () => { const opacity = ['opacity: 0;', 'opacity: 1;']; const opacityAnimation = keyframes` from { ${opacity[0]} } to { ${opacity[1]} } `; const slideAnimation = keyframes` from { transform: translateX(-10px); } to { transform: none; } `; const getAnimation = (animation: any): any => { if (Array.isArray(animation)) { return animation.reduce( (ret, a, index) => css` ${ret}${index > 0 ? ',' : ''} ${getAnimation(a)} `, '' ); } else { return css` ${animation === 'slide' ? slideAnimation : opacityAnimation} 1s linear `; } }; const Foo = styled.div<{ animation?: any }>` animation: ${props => (props.animation ? getAnimation(props.animation) : 'none')}; `; const App = () => ( <React.Fragment> <Foo>hi</Foo> <Foo animation={['slide', 'fade']}>hi, I slide and fade.</Foo> <Foo animation="fade">hi I fade</Foo> <Foo animation="slide">hi I slide</Foo> </React.Fragment> ); TestRenderer.create(<App />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".d { animation: none; } .e { animation: b 1s linear, a 1s linear; } .f { animation: a 1s linear; } .g { animation: b 1s linear; } @keyframes b { from { transform: translateX(-10px); } to { transform: none; } } @keyframes a { from { opacity: 0; } to { opacity: 1; } }" `); }); it('should throw an error when interpolated in a vanilla string', () => { const animation = keyframes``; expect(() => `animation-name: ${animation};`).toThrow(); }); it('should use the local stylis instance', () => { const rules = ` 0% { left: 0%; } 100% { left: 100%; } `; const animation = keyframes`${rules}`; expect(getRenderedCSS()).toMatchInlineSnapshot(`""`); const Comp = styled.div` animation: ${animation} 2s linear infinite; `; TestRenderer.create( <StyleSheetManager stylisPlugins={[stylisRTLPlugin]}> <Comp /> </StyleSheetManager> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".c { animation: a-1567285458 2s linear infinite; } @keyframes a-1567285458 { 0% { right: 0%; } 100% { right: 100%; } }" `); }); it('should reinject if used in different stylis contexts', () => { const rules = ` 0% { left: 0%; } 100% { left: 100%; } `; const animation = keyframes`${rules}`; expect(getRenderedCSS()).toMatchInlineSnapshot(`""`); const Comp = styled.div` animation: ${animation} 2s linear infinite; `; TestRenderer.create( <> <Comp /> <StyleSheetManager stylisPlugins={[stylisRTLPlugin]}> <Comp /> </StyleSheetManager> </> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".c { animation: a 2s linear infinite; } .d { animation: a-1567285458 2s linear infinite; } @keyframes a { 0% { left: 0%; } 100% { left: 100%; } } @keyframes a-1567285458 { 0% { right: 0%; } 100% { right: 100%; } }" `); }); it('namespaced StyleSheetManager works with animations', () => { const rotate = keyframes` 0% { transform: rotate(0deg) } 100% { transform: rotate(360deg) } `; const TestAnim = styled.div` color: blue; animation: ${rotate} 0.75s infinite linear; `; TestRenderer.create( <StyleSheetManager namespace=".animparent"> <div> <TestAnim>Foo</TestAnim> </div> </StyleSheetManager> ); expect(document.head.innerHTML).toMatchInlineSnapshot(` <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > .animparent .c{color:blue;animation:a 0.75s infinite linear;}@keyframes a{0%{transform:rotate(0deg);}100%{transform:rotate(360deg);}} </style> `); }); });
3,025
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/constructors
petrpan-code/styled-components/styled-components/packages/styled-components/src/constructors/test/styled.test.tsx
import React, { ComponentProps } from 'react'; import TestRenderer from 'react-test-renderer'; import { getRenderedCSS, resetStyled } from '../../test/utils'; import domElements from '../../utils/domElements'; let styled: ReturnType<typeof resetStyled>; describe('styled', () => { beforeEach(() => { styled = resetStyled(); }); it('should have all valid HTML5 elements defined as properties', () => { domElements.forEach(domElement => { expect(styled[domElement]).toBeTruthy(); }); }); it('should expose the component static attribute like components', () => { const CollapseComponent = (props: ComponentProps<'div'>) => { return <div {...props} />; }; const Panel = (props: ComponentProps<'div'>) => { return <div {...props} />; }; const Collapse = Object.assign(CollapseComponent, { Panel, PI: '3.14' }); const StyledCollapse = styled(Collapse)` background: red; `; expect(Collapse).toBeTruthy(); expect(Collapse.Panel).toBeTruthy(); expect(Collapse.PI).toBe('3.14'); expect(StyledCollapse).toBeTruthy(); expect(StyledCollapse.Panel).toBeTruthy(); expect(StyledCollapse.PI).toBe('3.14'); TestRenderer.create(<StyledCollapse />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { background: red; }" `); }); });
3,037
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/models
petrpan-code/styled-components/styled-components/packages/styled-components/src/models/test/Keyframes.test.ts
import Keyframes from '../Keyframes'; describe('Keyframes', () => { it('should throw an error when converted to string', () => { const keyframes = new Keyframes('foo', 'bar'); expect(() => keyframes.toString()).toThrowError( /It seems you are interpolating a keyframe declaration \(foo\) into an untagged string./ ); }); });
3,038
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/models
petrpan-code/styled-components/styled-components/packages/styled-components/src/models/test/StyleSheetManager.test.tsx
import React from 'react'; import { render } from 'react-dom'; import { renderToString } from 'react-dom/server'; import Frame, { FrameContextConsumer } from 'react-frame-component'; import TestRenderer, { act } from 'react-test-renderer'; import stylisRTLPlugin from 'stylis-plugin-rtl'; import StyleSheet from '../../sheet'; import { resetStyled } from '../../test/utils'; import ServerStyleSheet from '../ServerStyleSheet'; import { StyleSheetManager } from '../StyleSheetManager'; let styled: ReturnType<typeof resetStyled>; describe('StyleSheetManager', () => { beforeEach(() => { document.body.innerHTML = ''; document.head.innerHTML = ''; styled = resetStyled(true); jest.spyOn(console, 'error').mockImplementation(() => {}); jest.spyOn(console, 'warn').mockImplementation(() => {}); }); it('should use given stylesheet instance', () => { const serverStyles = new ServerStyleSheet(); const Title = styled.h1` color: palevioletred; `; renderToString( <StyleSheetManager sheet={serverStyles.instance}> <Title /> </StyleSheetManager> ); expect(serverStyles.getStyleTags().includes(`palevioletred`)).toEqual(true); }); it('should render its child', () => { const target = document.head; const Title = styled.h1` color: palevioletred; `; const renderedComp = TestRenderer.create( <StyleSheetManager target={target}> <Title /> </StyleSheetManager> ); expect(() => renderedComp.root.findByType(Title)).not.toThrowError(); }); it('should append style to given target', () => { const target = document.body; const Title = styled.h1` color: palevioletred; `; class Child extends React.Component { render() { return <Title />; } } expect(document.body.querySelectorAll('style')).toHaveLength(0); TestRenderer.create( <StyleSheetManager target={target}> <Child /> </StyleSheetManager> ); const styles = target.querySelector('style')?.textContent; expect(styles?.includes(`palevioletred`)).toEqual(true); }); it('should append style to given target in iframe', () => { const iframe = document.createElement('iframe'); const app = document.createElement('div'); document.body.appendChild(iframe); iframe.contentDocument!.body.appendChild(app); const target = iframe.contentDocument!.head; const Title = styled.h1` color: palevioletred; `; class Child extends React.Component { render() { return <Title />; } } render( <StyleSheetManager target={target}> <Child /> </StyleSheetManager>, app ); const styles = target.querySelector('style')?.textContent; expect(styles?.includes(`palevioletred`)).toEqual(true); }); it('should apply styles to appropriate targets for nested StyleSheetManagers', () => { const ONE = styled.h1` color: red; `; const TWO = styled.h2` color: blue; `; const THREE = styled.h3` color: green; `; TestRenderer.create( <div> <ONE /> <StyleSheetManager target={document.head}> <div> <TWO /> <StyleSheetManager target={document.body}> <THREE /> </StyleSheetManager> </div> </StyleSheetManager> </div> ); expect(document.head.innerHTML).toMatchSnapshot(); expect(document.body.innerHTML).toMatchSnapshot(); }); // https://github.com/styled-components/styled-components/issues/1634 it('should inject styles into two parallel contexts', async () => { const Title = styled.h1` color: palevioletred; `; // Injects the stylesheet into the document available via context const SheetInjector = ({ children, target }: any) => ( <StyleSheetManager target={target}>{children}</StyleSheetManager> ); class Child extends React.Component<{ document: Document; resolve: Function }> { componentDidMount() { const styles = this.props.document.querySelector('style')?.textContent; expect(styles?.includes(`palevioletred`)).toEqual(true); this.props.resolve(); } render() { return <Title />; } } const div = document.body.appendChild(document.createElement('div')); let promiseB; const promiseA = new Promise((resolveA, reject) => { promiseB = new Promise(resolveB => { try { // Render two iframes. each iframe should have the styles for the child injected into their head render( <div> <Frame> <FrameContextConsumer> {({ document }) => ( <SheetInjector target={document!.head}> <Child document={document!} resolve={resolveA} /> </SheetInjector> )} </FrameContextConsumer> </Frame> <Frame> <FrameContextConsumer> {({ document }) => ( <SheetInjector target={document!.head}> <Child document={document!} resolve={resolveB} /> </SheetInjector> )} </FrameContextConsumer> </Frame> </div>, div ); } catch (e) { reject(e); div.parentElement!.removeChild(div); } }); }); await Promise.all([promiseA, promiseB]); div.parentElement!.removeChild(div); }); // https://github.com/styled-components/styled-components/issues/2973 it('should inject common styles into both the main document and a child frame', async () => { const CommonTitle = styled.h1` color: palevioletred; `; // Injects the stylesheet into the document available via context const SheetInjector = ({ children, target }: any) => ( <StyleSheetManager target={target}>{children}</StyleSheetManager> ); class Main extends React.Component<{ document: Document }> { componentDidMount() { const styles = this.props.document.querySelector('style')?.textContent; expect(styles?.includes('palevioletred')).toEqual(true); } render() { return this.props.children; } } class Child extends React.Component<{ document: Document }> { componentDidMount() { const styles = this.props.document.querySelector('style')?.textContent; expect(styles?.includes(`palevioletred`)).toEqual(true); } render() { return <CommonTitle />; } } const div = document.body.appendChild(document.createElement('div')); render( <Main document={document}> <div> <CommonTitle /> <Frame> <FrameContextConsumer> {({ document }) => ( <SheetInjector target={document!.head}> <Child document={document!} /> </SheetInjector> )} </FrameContextConsumer> </Frame> </div> </Main>, div ); div.parentElement!.removeChild(div); }); it('should render styles in correct order when styled(StyledComponent) and StyleSheetManager is used', () => { const Red = styled.div` color: red; `; const RedChangedToBlue = styled(Red)` color: blue; `; const sheet = new StyleSheet(); const App = () => ( <StyleSheetManager sheet={sheet}> <RedChangedToBlue>I should be blue</RedChangedToBlue> </StyleSheetManager> ); const attachPoint = document.body.appendChild(document.createElement('div')); render(<App />, attachPoint); // window.getComputedStyles would be perfect, but it seems that JSDOM // implementation of that function isn't complete, so need to work around // it. const source = document.documentElement.outerHTML; // regex in case test is run against minified CSS in the future const indexOfRedStyle = source.search('color:red'); const indexOfBlueStyle = source.search('color:blue'); expect(indexOfRedStyle).toBeGreaterThanOrEqual(0); expect(indexOfBlueStyle).toBeGreaterThanOrEqual(0); expect(indexOfBlueStyle).toBeGreaterThan(indexOfRedStyle); }); it('passing `enableVendorPrefixes` to StyleSheetManager works', () => { const Test = styled.div` display: flex; `; TestRenderer.create( <StyleSheetManager enableVendorPrefixes> <Test>Foo</Test> </StyleSheetManager> ); expect(document.head.innerHTML).toMatchInlineSnapshot(` <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > .b{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;} </style> `); }); it('passing default shouldForwardProp via StyleSheetManager works', () => { const Test = styled.div<{ foo?: boolean; bar?: boolean }>` padding-left: 5px; `; const result = TestRenderer.create( <StyleSheetManager shouldForwardProp={p => (p === 'foo' ? false : true)}> <Test foo bar> Foo </Test> </StyleSheetManager> ); expect(result.toJSON()).toMatchInlineSnapshot(` <div bar={true} className="sc-a b" > Foo </div> `); }); it('passing stylis plugins via StyleSheetManager works', () => { const Test = styled.div` padding-left: 5px; `; TestRenderer.create( <StyleSheetManager stylisPlugins={[stylisRTLPlugin]}> <Test>Foo</Test> </StyleSheetManager> ); expect(document.head.innerHTML).toMatchInlineSnapshot(` <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > .b{padding-right:5px;} </style> `); }); it('an error is emitted if unnamed stylis plugins are provided', () => { const Test = styled.div` padding-left: 5px; `; const cachedName = stylisRTLPlugin.name; Object.defineProperty(stylisRTLPlugin, 'name', { value: undefined }); expect(() => TestRenderer.create( <StyleSheetManager stylisPlugins={[stylisRTLPlugin]}> <Test>Foo</Test> </StyleSheetManager> ) ).toThrowError(); Object.defineProperty(stylisRTLPlugin, 'name', { value: cachedName }); }); it('changing stylis plugins via StyleSheetManager works', () => { const Test = styled.div` padding-left: 5px; `; const wrapper = TestRenderer.create( <StyleSheetManager stylisPlugins={[stylisRTLPlugin]}> <Test>Foo</Test> </StyleSheetManager> ); expect(document.head.innerHTML).toMatchInlineSnapshot(` <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > .b{padding-right:5px;} </style> `); expect(wrapper.toJSON()).toMatchInlineSnapshot(` <div className="sc-a b" > Foo </div> `); act(() => { wrapper.update( <StyleSheetManager> <Test>Foo</Test> </StyleSheetManager> ); }); // note that the old styles are not removed since the condition may appear where they're used again expect(document.head.innerHTML).toMatchInlineSnapshot(` <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > .b{padding-right:5px;}.c{padding-left:5px;} </style> `); expect(wrapper.toJSON()).toMatchInlineSnapshot(` <div className="sc-a c" > Foo </div> `); act(() => { wrapper.update( <StyleSheetManager stylisPlugins={[stylisRTLPlugin]}> <Test>Foo</Test> </StyleSheetManager> ); }); // no new dynamic classes are added, reusing the prior one expect(document.head.innerHTML).toMatchInlineSnapshot(` <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > .b{padding-right:5px;}.c{padding-left:5px;} </style> `); expect(wrapper.toJSON()).toMatchInlineSnapshot(` <div className="sc-a b" > Foo </div> `); }); it('subtrees with different stylis configs should not conflict', () => { const Test = styled.div` padding-left: 5px; `; const wrapper = TestRenderer.create( <div> <Test>Bar</Test> <StyleSheetManager stylisPlugins={[stylisRTLPlugin]}> <Test>Foo</Test> </StyleSheetManager> </div> ); expect(document.head.innerHTML).toMatchInlineSnapshot(` <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > .b{padding-left:5px;}.c{padding-right:5px;} </style> `); expect(wrapper.toJSON()).toMatchInlineSnapshot(` <div> <div className="sc-a b" > Bar </div> <div className="sc-a c" > Foo </div> </div> `); }); it('nested StyleSheetManager with different injection modes works', () => { const Test = styled.div` padding-left: 5px; `; const Test2 = styled.div` background: red; `; const outerSheet = new StyleSheet({ useCSSOMInjection: true }); TestRenderer.create( <StyleSheetManager sheet={outerSheet}> <div> <Test>Foo</Test> <StyleSheetManager disableCSSOMInjection> <Test2>Bar</Test2> </StyleSheetManager> </div> </StyleSheetManager> ); expect(outerSheet.getTag().tag.getRule(0)).toMatchInlineSnapshot(`".c {padding-left: 5px;}"`); expect(document.head.innerHTML).toMatchInlineSnapshot(` <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > </style> <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > .d{background:red;} </style> `); }); it('passing a namespace to StyleSheetManager works', () => { const Test = styled.div` display: flex; `; TestRenderer.create( <StyleSheetManager namespace="#foo"> <Test>Foo</Test> </StyleSheetManager> ); expect(document.head.innerHTML).toMatchInlineSnapshot(` <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > #foo .b{display:flex;} </style> `); }); it('nested StyleSheetManager with different namespaces works', () => { const Test = styled.div` padding-left: 5px; `; const Test2 = styled.div` background: red; `; TestRenderer.create( <StyleSheetManager namespace="#foo"> <div> <Test>Foo</Test> <StyleSheetManager namespace="#bar"> <Test2>Bar</Test2> </StyleSheetManager> </div> </StyleSheetManager> ); expect(document.head.innerHTML).toMatchInlineSnapshot(` <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > #foo .c{padding-left:5px;}#bar .d{background:red;} </style> `); }); it('namespaced StyleSheetManager works with ampersand selector', () => { const Test = styled.div` padding-top: 5px; .child & { padding-top: 10px; } `; TestRenderer.create( <StyleSheetManager namespace=".parent"> <div> <Test>Foo</Test> <div className="child"> <Test>Foo Bar</Test> </div> </div> </StyleSheetManager> ); expect(document.head.innerHTML).toMatchInlineSnapshot(` <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > .parent .b{padding-top:5px;}.parent .child .b{padding-top:10px;} </style> `); }); it('namespaced StyleSheetManager works with ampersand selector (complex)', () => { const Test = styled.div` color: red; .child2 &, .child & { color: green; } `; TestRenderer.create( <StyleSheetManager namespace=".parent"> <div> <Test>Foo</Test> <div className="child"> <Test>Foo Bar</Test> </div> <div className="child2"> <Test>Foo Bar</Test> </div> </div> </StyleSheetManager> ); expect(document.head.innerHTML).toMatchInlineSnapshot(` <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > .parent .b{color:red;}.parent .child2 .b,.parent .child .b{color:green;} </style> `); }); it('namespaced StyleSheetManager works with ampersand selector and media queries', () => { const Test = styled.div` color: red; .child2 &, .child & { color: green; } @media (min-width: 768px) { color: blue; .child2 &, .child & { color: cyan; } } `; TestRenderer.create( <StyleSheetManager namespace=".parent"> <div> <Test>Foo</Test> <div className="child"> <Test>Foo Bar</Test> </div> <div className="child2"> <Test>Foo Bar</Test> </div> </div> </StyleSheetManager> ); expect(document.head.innerHTML).toMatchInlineSnapshot(` <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > .parent .b{color:red;}.parent .child2 .b,.parent .child .b{color:green;}@media (min-width: 768px){.parent .b{color:blue;}.parent .child2 .b,.parent .child .b{color:cyan;}} </style> `); }); });
3,039
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/models
petrpan-code/styled-components/styled-components/packages/styled-components/src/models/test/ThemeProvider.test.tsx
import React from 'react'; import TestRenderer, { ReactTestInstance } from 'react-test-renderer'; import withTheme from '../../hoc/withTheme'; import { resetStyled } from '../../test/utils'; import ThemeProvider, { useTheme } from '../ThemeProvider'; let styled: ReturnType<typeof resetStyled>; describe('ThemeProvider', () => { beforeEach(() => { styled = resetStyled(); }); it('should not throw an error when no children are passed', () => { TestRenderer.create(<ThemeProvider theme={{}} />); }); it("should accept a theme prop that's a plain object", () => { TestRenderer.create(<ThemeProvider theme={{ main: 'black' }} />); }); it('should render its child', () => { const child = <p>Child!</p>; const wrapper = TestRenderer.create( <ThemeProvider theme={{ main: 'black' }}>{child}</ThemeProvider> ); expect(wrapper.toJSON()).toMatchSnapshot(); }); it('should merge its theme with an outer theme', () => { const outerTheme = { main: 'black' }; const innerTheme = { secondary: 'black' }; const MyDiv = styled.div``; const MyDivWithTheme = withTheme(MyDiv); const wrapper = TestRenderer.create( <ThemeProvider theme={outerTheme}> <ThemeProvider theme={innerTheme}> <MyDivWithTheme /> </ThemeProvider> </ThemeProvider> ); expect(wrapper.root.findByType(MyDiv).props.theme).toEqual({ ...outerTheme, ...innerTheme, }); }); it('should merge its theme with multiple outer themes', () => { const outerestTheme = { main: 'black' }; const outerTheme = { main: 'blue' }; const innerTheme = { secondary: 'black' }; const MyDiv = styled.div``; const MyDivWithTheme = withTheme(MyDiv); const wrapper = TestRenderer.create( <ThemeProvider theme={outerestTheme}> <ThemeProvider theme={outerTheme}> <ThemeProvider theme={innerTheme}> <MyDivWithTheme /> </ThemeProvider> </ThemeProvider> </ThemeProvider> ); expect(wrapper.root.findByType(MyDiv).props.theme).toEqual({ ...outerestTheme, ...outerTheme, ...innerTheme, }); }); it('should be able to render two independent themes', () => { const themes = { one: { main: 'black', secondary: 'red' }, two: { main: 'blue', other: 'green' }, }; const MyDivOne = withTheme(styled.div``); const MyDivWithThemeOne = withTheme(MyDivOne); const MyDivTwo = withTheme(styled.div``); const MyDivWithThemeTwo = withTheme(MyDivTwo); const wrapper = TestRenderer.create( <div> <ThemeProvider theme={themes.one}> <MyDivWithThemeOne /> </ThemeProvider> <ThemeProvider theme={themes.two}> <MyDivWithThemeTwo /> </ThemeProvider> </div> ); expect(wrapper.root.findByType(MyDivOne).props.theme).toEqual(themes.one); expect(wrapper.root.findByType(MyDivTwo).props.theme).toEqual(themes.two); }); it('ThemeProvider propagates theme updates through nested ThemeProviders', () => { const theme = { themed: true }; const augment = (outerTheme: typeof theme) => Object.assign({}, outerTheme, { augmented: true }); const update = { updated: true }; const expected = { themed: true, augmented: true, updated: true }; const MyDiv = styled.div``; const MyDivWithTheme = withTheme(MyDiv); const getJSX = (givenTheme = theme) => ( <ThemeProvider theme={givenTheme}> <ThemeProvider theme={augment}> <MyDivWithTheme /> </ThemeProvider> </ThemeProvider> ); const wrapper = TestRenderer.create(getJSX()); wrapper.update(getJSX(Object.assign({}, theme, update))); expect(wrapper.root.findByType(MyDiv).props.theme).toEqual(expected); }); }); describe('useTheme', () => { beforeEach(() => { styled = resetStyled(); }); it('useTheme should get the same theme that is serving ThemeProvider', () => { const mainTheme = { main: 'black' }; const MyDivOne = withTheme(styled.div``); const MyDivWithThemeOne = withTheme(MyDivOne); const MyDivWithThemeContext = () => { const theme = useTheme(); return <div data-theme={theme} />; }; const wrapper = TestRenderer.create( <div> <ThemeProvider theme={mainTheme}> <React.Fragment> <MyDivWithThemeOne /> <MyDivWithThemeContext /> </React.Fragment> </ThemeProvider> </div> ); expect(wrapper.root.findByType(MyDivOne).props.theme).toEqual(mainTheme); expect( (wrapper.root.findByType(MyDivWithThemeContext).children[0] as ReactTestInstance).props[ 'data-theme' ] ).toEqual(mainTheme); }); });
3,040
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/models/test
petrpan-code/styled-components/styled-components/packages/styled-components/src/models/test/__snapshots__/StyleSheetManager.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`StyleSheetManager should apply styles to appropriate targets for nested StyleSheetManagers 1`] = ` <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > .d{color:red;} </style> <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > .e{color:blue;} </style> `; exports[`StyleSheetManager should apply styles to appropriate targets for nested StyleSheetManagers 2`] = ` <style data-styled="active" data-styled-version="JEST_MOCK_VERSION" > .f{color:green;} </style> `;
3,041
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/models/test
petrpan-code/styled-components/styled-components/packages/styled-components/src/models/test/__snapshots__/ThemeProvider.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`ThemeProvider should render its child 1`] = ` <p> Child! </p> `;
3,043
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/native
petrpan-code/styled-components/styled-components/packages/styled-components/src/native/test/native.test.tsx
import React, { PropsWithChildren } from 'react'; import { Image, Text, View, ViewProps } from 'react-native'; import TestRenderer from 'react-test-renderer'; import styled, { ThemeProvider, css, toStyleSheet } from '../'; // NOTE: These tests are like the ones for Web but a "light-version" of them // This is mostly due to the similar logic describe('native', () => { it('should not throw an error when called with a valid element', () => { expect(() => styled.View``).not.toThrowError(); const FunctionalComponent = () => <View />; class ClassComponent extends React.Component { render() { return <View />; } } const validComps = ['View', FunctionalComponent, ClassComponent]; validComps.forEach(comp => { expect(() => { // @ts-expect-error invalid input const Comp = styled(comp)``; TestRenderer.create(<Comp />); }).not.toThrowError(); }); }); it('should generate inline styles', () => { const Comp = styled.View``; const wrapper = TestRenderer.create(<Comp />); const view = wrapper.root.findByType(View); expect(view.props.style).toEqual({}); }); it('should fold successive styled() wrappings', () => { const Comp = styled.Text` color: red; `; const Comp2 = styled(Comp)` text-align: left; `; const wrapper = TestRenderer.create(<Comp2 />); const view = wrapper.root.findByType(Text); expect(view.props.style).toEqual({ color: 'red', textAlign: 'left' }); }); it('folds defaultProps', () => { const Inner = styled.View<ViewProps>``; Inner.defaultProps = { theme: { fontSize: 12, }, style: { backgroundColor: 'blue', }, }; const Outer = styled(Inner)``; Outer.defaultProps = { theme: { fontSize: 16, }, style: { backgroundColor: 'silver', }, }; expect(Outer.defaultProps).toMatchInlineSnapshot(` { "style": { "backgroundColor": "silver", }, "theme": { "fontSize": 16, }, } `); }); it('should combine inline styles and the style prop', () => { const Comp = styled.View` padding-top: 10px; `; const style = { opacity: 0.9 }; const wrapper = TestRenderer.create(<Comp style={style} />); const view = wrapper.root.findByType(View); expect(view.props.style).toEqual([{ paddingTop: 10 }, style]); }); it('should not console.warn if a comment is seen', () => { const oldConsoleWarn = console.warn; console.warn = jest.fn(); try { styled.View` /* this is a comment */ `; expect(console.warn).not.toHaveBeenCalled(); } finally { console.warn = oldConsoleWarn; } }); // https://github.com/styled-components/styled-components/issues/1266 it('should update when props change', () => { const Comp = styled.View<{ opacity?: number }>` padding-top: 5px; opacity: ${p => p.opacity || 0}; `; const wrapper = TestRenderer.create(<Comp opacity={0.5} />); expect(wrapper.root.findByType(View).props.style).toEqual({ paddingTop: 5, opacity: 0.5 }); wrapper.update(<Comp opacity={0.9} />); expect(wrapper.root.findByType(View).props.style).toEqual({ paddingTop: 5, opacity: 0.9 }); }); it('should forward the "as" prop if "forwardedAs" is used', () => { const Comp = ({ as: Component = View, ...props }) => <Component {...props} />; const Comp2 = styled(Comp)` background: red; `; const wrapper = TestRenderer.create(<Comp2 forwardedAs={Text} />); expect(wrapper.root.findByType(Text)).not.toBeUndefined(); }); it('should not add different border values for Image component as its not supported', () => { const Comp = styled.Image` border-width: 10px; border-color: red; `; const loremPicsumUri = 'https://picsum.photos/200/300'; const wrapper = TestRenderer.create(<Comp source={{ uri: loremPicsumUri }} />); const image = wrapper.root.findByType(Image); expect(image.props.style).toEqual({ borderWidth: 10, borderColor: 'red' }); }); describe('attrs', () => { beforeEach(() => jest.spyOn(console, 'warn').mockImplementation(() => {})); it('works fine with an empty object', () => { const Comp = styled.View.attrs(() => ({}))``; const wrapper = TestRenderer.create(<Comp />); const view = wrapper.root.findByType(View); expect(view.props).toEqual({ style: {}, }); }); interface TestProps { first?: string; second?: string; test?: string | boolean; copy?: string; } const ComponentWithProps = styled.View<TestProps>``; it('passes simple props on', () => { const Comp = styled(ComponentWithProps).attrs(() => ({ test: true, }))``; const wrapper = TestRenderer.create(<Comp />); const view = wrapper.root.findByType(View); expect(view.props).toEqual({ style: {}, test: true, }); }); it('calls an attr-function with context', () => { const Comp = styled(ComponentWithProps).attrs<{ copy?: string; test: string }>(p => ({ copy: p.test, }))``; const test = 'Put that cookie down!'; const wrapper = TestRenderer.create(<Comp test={test} />); const view = wrapper.root.findByType(View); expect(view.props).toEqual({ style: {}, copy: test, test, }); }); it('merges multiple calls', () => { const Comp = styled(ComponentWithProps) .attrs(() => ({ first: 'first', test: '_', })) .attrs(() => ({ second: 'second', test: 'test', }))``; const wrapper = TestRenderer.create(<Comp />); const view = wrapper.root.findByType(View); expect(view.props).toEqual({ style: {}, first: 'first', second: 'second', test: 'test', }); }); it('merges multiple fn calls', () => { const ComponentWithProps = styled.View<TestProps>``; const Comp = styled(ComponentWithProps) .attrs(() => ({ first: 'first', test: '_', })) .attrs(() => ({ second: 'second', test: 'test', }))``; const wrapper = TestRenderer.create(<Comp />); const view = wrapper.root.findByType(View); expect(view.props).toEqual({ style: {}, first: 'first', second: 'second', test: 'test', }); }); it('merges attrs when inheriting SC', () => { const Parent = styled(ComponentWithProps).attrs(() => ({ first: 'first', }))``; const Child = styled(Parent).attrs(() => ({ second: 'second', }))``; const wrapper = TestRenderer.create(<Child />); const view = wrapper.root.findByType(View); expect(view.props).toMatchObject({ style: {}, first: 'first', second: 'second', }); }); it('should pass through children as a normal prop', () => { const Comp = styled.Text.attrs(() => ({ children: 'Probably a bad idea', }))``; const wrapper = TestRenderer.create(<Comp />); const text = wrapper.root.findByType(Text); expect(text.props).toMatchObject({ children: 'Probably a bad idea', style: {}, }); }); it('should pass through complex children as well', () => { const child = <Text>Probably a bad idea</Text>; const Comp = styled.Text.attrs(() => ({ children: child, }))``; const wrapper = TestRenderer.create(<Comp />); const text = wrapper.root.findByType(Text); expect(text.props).toMatchObject({ children: child, style: {}, }); }); it('should override children', () => { const child = <Text>Amazing</Text>; const Comp = styled.Text.attrs(() => ({ children: child, }))``; const wrapper = TestRenderer.create(<Comp>Something else</Comp>); const text = wrapper.root.findByType(Text); expect(text.props).toMatchObject({ children: child, style: {}, }); }); it('accepts a function', () => { const child = <Text>Amazing</Text>; const Comp = styled.Text.attrs(() => ({ children: child, }))``; const wrapper = TestRenderer.create(<Comp>Something else</Comp>); const text = wrapper.root.findByType(Text); expect(text.props).toMatchObject({ children: child, style: {}, }); }); it('function form allows access to theme', () => { const Comp = styled.Text.attrs(props => ({ selectionColor: props.theme.color, }))``; const wrapper = TestRenderer.create( <ThemeProvider theme={{ color: 'red' }}> <Comp>Something else</Comp> </ThemeProvider> ); const text = wrapper.root.findByType(Text); expect(text.props).toMatchObject({ children: 'Something else', selectionColor: 'red', style: {}, }); }); it('theme prop works', () => { const Comp = styled.Text` color: ${({ theme }) => theme.myColor}; `; const wrapper = TestRenderer.create(<Comp theme={{ myColor: 'red' }}>Something else</Comp>); const text = wrapper.root.findByType(Text); expect(text.props.style).toMatchObject({ color: 'red' }); }); it('theme in defaultProps works', () => { const Comp = styled.Text` color: ${({ theme }) => theme.myColor}; `; Comp.defaultProps = { theme: { myColor: 'red' } }; const wrapper = TestRenderer.create(<Comp>Something else</Comp>); const text = wrapper.root.findByType(Text); expect(text.props.style).toMatchObject({ color: 'red' }); }); it('convert css to styleSheet', () => { const cssStyle = css` background-color: red; border-width: 10px; `; expect(toStyleSheet(cssStyle)).toEqual({ backgroundColor: 'red', borderWidth: 10 }); }); }); describe('expanded API', () => { it('should attach a displayName', () => { const Dummy = (props: PropsWithChildren<{}>) => <View {...props} />; Dummy.displayName = 'Dummy'; const Comp = styled(Dummy)``; expect(Comp.displayName).toBe('Styled(Dummy)'); const CompTwo = styled.View.withConfig({ displayName: 'Test' })``; expect(CompTwo.displayName).toBe('Test'); }); it('should allow multiple calls to be chained', () => { const Comp = styled.View.withConfig({ displayName: 'Test1' }).withConfig({ displayName: 'Test2', })``; expect(Comp.displayName).toBe('Test2'); }); it('"as" prop should change the rendered element without affecting the styling', () => { // @ts-expect-error foo is expected later in the test const OtherText = (props: PropsWithChildren<{}>) => <Text {...props} foo />; const Comp = styled.Text` color: red; `; const wrapper = TestRenderer.create(<Comp as={OtherText} />); const view = wrapper.root.findByType(Text); expect(view.props).toHaveProperty('foo'); expect(view.props.style).toEqual({ color: 'red' }); }); it('should omit transient props', () => { const Comp = styled.Text<{ $color: string }>` color: ${p => p.$color}; `; expect(TestRenderer.create(<Comp $color="red" />).toJSON()).toMatchInlineSnapshot(` <Text style={ { "color": "red", } } /> `); }); it('allows for custom prop filtering for elements', () => { const Comp = styled.View.withConfig({ shouldForwardProp: prop => !['filterThis'].includes(prop), })<{ filterThis: string; passThru: string }>` color: red; `; const wrapper = TestRenderer.create(<Comp filterThis="abc" passThru="def" />); // @ts-expect-error bs error const { props } = wrapper.root.findByType('View'); expect(props.style).toEqual({ color: 'red' }); expect(props.passThru).toBe('def'); expect(props.filterThis).toBeUndefined(); }); it('allows custom prop filtering for components', () => { const InnerComp = (props: PropsWithChildren<{}>) => <View {...props} />; const Comp = styled(InnerComp).withConfig({ shouldForwardProp: prop => !['filterThis'].includes(prop), })<{ filterThis?: string; passThru?: string }>` color: red; `; const wrapper = TestRenderer.create(<Comp filterThis="abc" passThru="def" />); // @ts-expect-error bs error const { props } = wrapper.root.findByType('View'); expect(props.style).toEqual({ color: 'red' }); expect(props.passThru).toBe('def'); expect(props.filterThis).toBeUndefined(); }); it('composes shouldForwardProp on composed styled components', () => { const StyledView = styled.View.withConfig({ shouldForwardProp: prop => prop === 'passThru', })<{ filterThis?: boolean; passThru?: boolean }>` color: red; `; const ComposedView = styled(StyledView).withConfig({ shouldForwardProp: () => true, })``; const wrapper = TestRenderer.create(<ComposedView filterThis passThru />); const { props } = wrapper.root.findByType(View); expect(props.passThru).toBeDefined(); expect(props.filterThis).toBeUndefined(); }); it('shouldForwardProp argument signature', () => { const stub = jest.fn(() => true); const StyledView = styled.View.withConfig({ shouldForwardProp: stub, })<{ something: boolean }>` color: red; `; TestRenderer.create(<StyledView something />); expect(stub.mock.calls).toMatchInlineSnapshot(` [ [ "something", [Function], ], ] `); // element being created // @ts-expect-error bad types expect(stub.mock.calls[0][1]).toEqual(View); }); it('should filter out props when using "as" to a custom component', () => { const AsComp = (props: PropsWithChildren<{}>) => <View {...props} />; const Comp = styled.View.withConfig({ shouldForwardProp: prop => !['filterThis'].includes(prop), })<{ filterThis: string; passThru: string }>` color: red; `; const wrapper = TestRenderer.create(<Comp as={AsComp} filterThis="abc" passThru="def" />); const { props } = wrapper.root.findByType(AsComp); expect(props.style).toEqual({ color: 'red' }); expect(props.passThru).toBe('def'); expect(props.filterThis).toBeUndefined(); }); it('can set computed styles based on props that are being filtered out', () => { const AsComp = (props: PropsWithChildren<{}>) => <View {...props} />; const Comp = styled.View.withConfig({ shouldForwardProp: prop => !['filterThis'].includes(prop), })<{ filterThis: string; passThru: string }>` color: ${props => (props.filterThis === 'abc' ? 'red' : undefined)}; `; const wrapper = TestRenderer.create(<Comp as={AsComp} filterThis="abc" passThru="def" />); const { props } = wrapper.root.findByType(AsComp); expect(props.style).toEqual({ color: 'red' }); expect(props.passThru).toBe('def'); expect(props.filterThis).toBeUndefined(); }); it('should filter our props when using "as" to a different element', () => { const Comp = styled.View.withConfig({ shouldForwardProp: prop => !['filterThis'].includes(prop), })<{ filterThis: string; passThru: string }>` color: red; `; const wrapper = TestRenderer.create(<Comp as={Text} filterThis="abc" passThru="def" />); const { props } = wrapper.root.findByType(Text); expect(props.style).toEqual({ color: 'red' }); expect(props.passThru).toBe('def'); expect(props.filterThis).toBeUndefined(); }); }); });
3,052
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/sheet
petrpan-code/styled-components/styled-components/packages/styled-components/src/sheet/test/GroupIDAllocator.test.ts
import * as GroupIDAllocator from '../GroupIDAllocator'; beforeEach(GroupIDAllocator.resetGroupIds); afterEach(GroupIDAllocator.resetGroupIds); it('creates continuous group IDs', () => { const a = GroupIDAllocator.getGroupForId('a'); const b = GroupIDAllocator.getGroupForId('b'); expect(a).toBe(1); expect(b).toBe(2); const a2 = GroupIDAllocator.getGroupForId('a'); expect(a2).toBe(a); const aId = GroupIDAllocator.getIdForGroup(a); expect(aId).toBe('a'); GroupIDAllocator.setGroupForId('b', 99); expect(GroupIDAllocator.getIdForGroup(99)).toBe('b'); expect(GroupIDAllocator.getGroupForId('b')).toBe(99); });
3,053
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/sheet
petrpan-code/styled-components/styled-components/packages/styled-components/src/sheet/test/GroupedTag.test.ts
import { makeGroupedTag } from '../GroupedTag'; import { VirtualTag } from '../Tag'; let tag: InstanceType<typeof VirtualTag>; let groupedTag: ReturnType<typeof makeGroupedTag>; beforeEach(() => { tag = new VirtualTag(); groupedTag = makeGroupedTag(tag); }); it('inserts and retrieves rules by groups correctly', () => { groupedTag.insertRules(2, ['.g2-a {}', '.g2-b {}']); // Insert out of order into the right group groupedTag.insertRules(1, ['.g1-a {}', '.g1-b {}']); groupedTag.insertRules(2, ['.g2-c {}', '.g2-d {}']); expect(groupedTag.length).toBeGreaterThan(2); expect(tag.length).toBe(6); // Expect groups to contain inserted rules expect(groupedTag.getGroup(0)).toBe(''); expect(groupedTag.getGroup(1)).toBe('.g1-a {}/*!sc*/\n.g1-b {}/*!sc*/\n'); expect(groupedTag.getGroup(2)).toBe( '.g2-a {}/*!sc*/\n.g2-b {}/*!sc*/\n' + '.g2-c {}/*!sc*/\n.g2-d {}/*!sc*/\n' ); // Check some rules in the tag as well expect(tag.getRule(3)).toBe('.g2-b {}'); expect(tag.getRule(0)).toBe('.g1-a {}'); // And the indices for sizes: [0, 2, 4, 0, ...] expect(groupedTag.indexOfGroup(0)).toBe(0); expect(groupedTag.indexOfGroup(1)).toBe(0); expect(groupedTag.indexOfGroup(2)).toBe(2); expect(groupedTag.indexOfGroup(3)).toBe(6); expect(groupedTag.indexOfGroup(4)).toBe(6); }); it('inserts rules at correct indices if some rules are dropped', () => { const tag = new VirtualTag(); jest.spyOn(tag, 'insertRule').mockImplementationOnce(() => false); const groupedTag = makeGroupedTag(tag); groupedTag.insertRules(1, ['.skipped {}', '.inserted {}']); expect(tag.length).toBe(1); expect(groupedTag.getGroup(1)).toBe('.inserted {}/*!sc*/\n'); }); it('inserts and deletes groups correctly', () => { groupedTag.insertRules(1, ['.g1-a {}']); expect(tag.length).toBe(1); expect(groupedTag.getGroup(1)).not.toBe(''); groupedTag.clearGroup(1); expect(tag.length).toBe(0); expect(groupedTag.getGroup(1)).toBe(''); // Noop test for non-existent group groupedTag.clearGroup(0); expect(tag.length).toBe(0); }); it('does supports large group numbers', () => { const baseSize = groupedTag.length; const group = 1 << 10; groupedTag.insertRules(group, ['.test {}']); // We expect the internal buffer to have grown beyond its initial size expect(groupedTag.length).toBeGreaterThan(baseSize); expect(groupedTag.length).toBeGreaterThan(group); expect(tag.length).toBe(1); expect(groupedTag.indexOfGroup(group)).toBe(0); expect(groupedTag.getGroup(group)).toBe('.test {}/*!sc*/\n'); }); it('throws when the upper group limit is reached', () => { const group = Math.pow(2, 31) + 1; // This can't be converted to an SMI to prevent cutoff expect(() => { groupedTag.insertRules(group, ['.test {}']); }).toThrowError(/reached the limit/i); });
3,054
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/sheet
petrpan-code/styled-components/styled-components/packages/styled-components/src/sheet/test/Rehydration.test.tsx
import React from 'react'; import TestRenderer from 'react-test-renderer'; import { ServerStyleSheet, StyleSheetManager } from '../../base'; import { SC_ATTR, SC_ATTR_ACTIVE, SC_ATTR_VERSION, SC_VERSION } from '../../constants'; import { resetStyled } from '../../test/utils'; import * as GroupIDAllocator from '../GroupIDAllocator'; import { outputSheet, rehydrateSheet } from '../Rehydration'; import StyleSheet from '../Sheet'; let styled: ReturnType<typeof resetStyled>; beforeEach(() => { GroupIDAllocator.resetGroupIds(); styled = resetStyled(); }); describe('outputSheet', () => { it('outputs sheets correctly', () => { const sheet = new StyleSheet({ isServer: true }); // Make the group numbers a little more arbitrary GroupIDAllocator.setGroupForId('idA', 11); GroupIDAllocator.setGroupForId('idB', 22); // Insert some rules sheet.insertRules('idA', 'nameA', ['.a {}']); sheet.insertRules('idB', 'nameB', ['.b {}']); const output = outputSheet(sheet).trim().split('/*!sc*/'); expect(output).toMatchInlineSnapshot(` [ ".a {}", " data-styled.g11[id="idA"]{content:"nameA,"}", " .b {}", " data-styled.g22[id="idB"]{content:"nameB,"}", "", ] `); }); }); describe('rehydrateSheet', () => { it('rehydrates sheets correctly', () => { document.head.innerHTML = ` <style ${SC_ATTR} ${SC_ATTR_VERSION}="${SC_VERSION}"> .a {}/*!sc*/ ${SC_ATTR}.g11[id="idA"]{content:"nameA,"}/*!sc*/ ${SC_ATTR}.g33[id="empty"]{content:""}/*!sc*/ </style> `; document.body.innerHTML = ` <style ${SC_ATTR} ${SC_ATTR_VERSION}="${SC_VERSION}"> .b {}/*!sc*/ ${SC_ATTR}.g22[id="idB"]{content:"nameB,"}/*!sc*/ </style> `; const styleHead = document.head.querySelector('style'); const styleBody = document.body.querySelector('style'); expect(styleHead!.parentElement).toBe(document.head); expect(styleBody!.parentElement).toBe(document.body); const sheet = new ServerStyleSheet(); rehydrateSheet(sheet.instance); // Adds ID to Group mapping to GroupIDAllocator expect(GroupIDAllocator.getIdForGroup(11)).toBe('idA'); expect(GroupIDAllocator.getIdForGroup(33)).toBe('empty'); expect(GroupIDAllocator.getIdForGroup(22)).toBe('idB'); // Registers ID + name combinations on the StyleSheet expect(sheet.instance.hasNameForId('idA', 'nameA')).toBe(true); expect(sheet.instance.hasNameForId('empty', 'empty')).toBe(false); expect(sheet.instance.hasNameForId('idB', 'nameB')).toBe(true); // Populates the underlying tag expect(sheet.instance.getTag().tag.length).toBe(2); expect(sheet.instance.getTag().getGroup(11)).toBe('.a {}/*!sc*/\n'); expect(sheet.instance.getTag().getGroup(22)).toBe('.b {}/*!sc*/\n'); expect(sheet.instance.getTag().getGroup(33)).toBe(''); // Removes the old tags expect(styleHead!.parentElement).toBe(null); expect(styleBody!.parentElement).toBe(null); const Foo = styled.div` color: burgundy; `; // new insertion is placed after the rehydrated styles TestRenderer.create( <StyleSheetManager sheet={sheet.instance}> <Foo /> </StyleSheetManager> ); expect(sheet.instance.getTag().tag.length).toBe(3); expect(sheet.getStyleTags()).toBe( ` <style data-styled=\"true\" data-styled-version=\"JEST_MOCK_VERSION\">.a {}/*!sc*/ data-styled.g11[id=\"idA\"]{content:\"nameA,\"}/*!sc*/ .b {}/*!sc*/ data-styled.g22[id=\"idB\"]{content:\"nameB,\"}/*!sc*/ .a{color:burgundy;}/*!sc*/ data-styled.g23[id=\"sc-kqxcKS\"]{content:\"a,\"}/*!sc*/ </style> `.trim() ); }); it('ignores active style elements', () => { document.head.innerHTML = ` <style ${SC_ATTR}="${SC_ATTR_ACTIVE}" ${SC_ATTR_VERSION}="${SC_VERSION}"> .a {}/*!sc*/ ${SC_ATTR}.g11[id="idA"]{content:"nameA,"}/*!sc*/ </style> `; const styleHead = document.head.querySelector('style'); expect(styleHead!.parentElement).toBe(document.head); const sheet = new StyleSheet({ isServer: true }); rehydrateSheet(sheet); expect(GroupIDAllocator.getIdForGroup(11)).toBe(undefined); expect(sheet.hasNameForId('idA', 'nameA')).toBe(false); expect(sheet.getTag().tag.length).toBe(0); expect(styleHead!.parentElement).toBe(document.head); }); it('tolerates long, malformed CSS', () => { document.head.innerHTML = ` <style ${SC_ATTR} ${SC_ATTR_VERSION}="${SC_VERSION}"> {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx } .rule {}/*!sc*/ ${SC_ATTR}.g1[id="idA"]{content:""}/*!sc*/ </style> `; const sheet = new StyleSheet({ isServer: true }); rehydrateSheet(sheet); }); });
3,055
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/sheet
petrpan-code/styled-components/styled-components/packages/styled-components/src/sheet/test/Sheet.test.ts
import StyleSheet from '../Sheet'; let sheet: InstanceType<typeof StyleSheet>; let tag; beforeEach(() => { sheet = new StyleSheet({ isServer: true }); tag = sheet.getTag().tag; }); it('inserts rules correctly', () => { expect(tag.length).toBe(0); sheet.insertRules('id', 'name', ['.test {}']); expect(sheet.hasNameForId('id', 'name')).toBe(true); expect(tag.length).toBe(1); }); it('allows to register and clear names for ids manually', () => { sheet.registerName('id', 'name'); expect(sheet.hasNameForId('id', 'name')).toBe(true); // The name and IDs are only unique in combination expect(sheet.hasNameForId('id', 'name2')).toBe(false); expect(sheet.hasNameForId('id2', 'name')).toBe(false); sheet.clearNames('id'); expect(sheet.hasNameForId('id', 'name')).toBe(false); }); it('clears rules correctly', () => { // First we insert an unaffected group sheet.insertRules('dummy', 'dummy', ['.unaffected {}']); expect(sheet.hasNameForId('dummy', 'dummy')).toBe(true); expect(tag.length).toBe(1); sheet.insertRules('id', 'name', ['.test {}']); expect(sheet.hasNameForId('id', 'name')).toBe(true); expect(tag.length).toBe(2); sheet.clearRules('id'); expect(tag.length).toBe(1); expect(sheet.hasNameForId('id', 'name')).toBe(false); expect(sheet.hasNameForId('dummy', 'dummy')).toBe(true); }); it('converts to string correctly', () => { sheet.insertRules('id', 'name', ['.test {}']); expect(sheet.toString()).toMatchInlineSnapshot(` ".test {}/*!sc*/ data-styled.g1[id="id"]{content:"name,"}/*!sc*/ " `); });
3,056
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/sheet
petrpan-code/styled-components/styled-components/packages/styled-components/src/sheet/test/Tag.test.ts
import { C } from 'ts-toolbelt'; import { CSSOMTag, TextTag, VirtualTag } from '../Tag'; import { Tag } from '../types'; const describeTag = (TagClass: C.Class<[], Tag>) => { it('inserts and retrieves rules at indices', () => { const tag = new TagClass(); expect(tag.insertRule(0, '.b {}')).toBe(true); expect(tag.insertRule(0, '.a {}')).toBe(true); expect(tag.insertRule(2, '.c {}')).toBe(true); expect(tag.insertRule(99, '.x {}')).toBe(false); expect(tag.getRule(0)).toBe('.a {}'); expect(tag.getRule(1)).toBe('.b {}'); expect(tag.getRule(2)).toBe('.c {}'); expect(tag.getRule(3)).toBe(''); expect(tag.length).toBe(3); }); it('deletes rules that have been inserted', () => { const tag = new TagClass(); expect(tag.insertRule(0, '.b {}')).toBe(true); expect(tag.length).toBe(1); tag.deleteRule(0); expect(tag.length).toBe(0); expect(tag.getRule(0)).toBe(''); }); }; describe('CSSOMTag', () => { describeTag(CSSOMTag); it('contains an empty TextNode to prevent an Edge quirk', () => { const tag = new CSSOMTag(); const { childNodes } = tag.element; expect(childNodes.length).toBe(1); expect(childNodes[0].nodeName).toBe('#text'); }); }); describe('TextTag', () => { describeTag(TextTag); }); describe('VirtualTag', () => { describeTag(VirtualTag); });
3,057
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/sheet
petrpan-code/styled-components/styled-components/packages/styled-components/src/sheet/test/dom.test.ts
import { SC_ATTR, SC_ATTR_ACTIVE, SC_ATTR_VERSION } from '../../constants'; import { makeStyleTag } from '../dom'; describe('makeStyleTag', () => { it('creates a style element with the SC attributes', () => { const element = makeStyleTag(); expect(element.tagName).toBe('STYLE'); expect(element.getAttribute(SC_ATTR)).toBe(SC_ATTR_ACTIVE); expect(element.hasAttribute(SC_ATTR_VERSION)).toBeTruthy(); }); it('inserts the element after all previously created ones', () => { const target = document.createElement('div'); target.innerHTML = ` <style data-index="1" ${SC_ATTR}></style> <div></div> <style data-index="2" ${SC_ATTR}></style> <div></div> <style data-index="3"></style> `; const element = makeStyleTag(target); const children = target.querySelectorAll('style'); expect(element.tagName).toBe('STYLE'); expect(children.length).toBe(4); expect(children[0].getAttribute('data-index')).toBe('1'); expect(children[1].getAttribute('data-index')).toBe('2'); expect(children[2]).toBe(element); expect(children[3].getAttribute('data-index')).toBe('3'); }); });
3,058
0
petrpan-code/styled-components/styled-components/packages/styled-components/src
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/attrs.test.tsx
import * as CSS from 'csstype'; import React from 'react'; import TestRenderer from 'react-test-renderer'; import ThemeProvider from '../models/ThemeProvider'; import { AnyComponent, DataAttributes } from '../types'; import { getRenderedCSS, resetStyled } from './utils'; // Disable isStaticRules optimisation since we're not // testing for ComponentStyle specifics here jest.mock('../utils/isStaticRules', () => () => false); let styled: ReturnType<typeof resetStyled>; describe('attrs', () => { beforeEach(() => { jest.spyOn(console, 'warn'); styled = resetStyled(); }); it('work fine with an empty object', () => { const Comp = styled.div.attrs({})``; expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); }); it('work fine with a function that returns an empty object', () => { const Comp = styled.div.attrs(() => ({}))``; expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); }); it('pass a simple attr via object', () => { const Comp = styled.button.attrs({ type: 'button', })``; expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); }); it('pass a simple attr via function with object return', () => { const Comp = styled.button.attrs(() => ({ type: 'button', }))``; expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); }); it('pass a React component', () => { class ReactComponent extends React.Component { render() { return <p>React Component</p>; } } type ButtonProps = { component: AnyComponent; }; const Button = ({ component: ChildComponent }: ButtonProps) => ( <button> <ChildComponent /> </button> ); const Comp = styled(Button).attrs<Partial<ButtonProps>>(() => ({ component: ReactComponent, }))``; expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); }); it('should not call a function passed to attrs as an object value', () => { const stub = jest.fn(() => 'div'); const Comp = styled.button.attrs<{ foo?: typeof stub }>(() => ({ foo: stub, }))``; TestRenderer.create(<Comp />); expect(stub).not.toHaveBeenCalled(); }); it('function form allows access to theme', () => { const Comp = styled.button.attrs<DataAttributes>(props => ({ 'data-color': props.theme!.color, }))``; expect( TestRenderer.create( <ThemeProvider theme={{ color: 'red' }}> <Comp /> </ThemeProvider> ).toJSON() ).toMatchInlineSnapshot(` <button className="sc-a" data-color="red" /> `); }); it('defaultProps are merged into what function attrs receives', () => { const Comp = styled.button.attrs<DataAttributes>(props => ({ 'data-color': props.theme!.color, }))``; Comp.defaultProps = { theme: { color: 'red', }, }; expect(TestRenderer.create(<Comp />).toJSON()).toMatchInlineSnapshot(` <button className="sc-a" data-color="red" /> `); }); it('pass props to the attr function', () => { const Comp = styled.button.attrs<{ $submit?: boolean }>(p => ({ type: p.$submit ? 'submit' : 'button', }))``; expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); expect(TestRenderer.create(<Comp $submit />).toJSON()).toMatchSnapshot(); }); it('should replace props with attrs', () => { const Comp = styled.button.attrs<{ $submit?: boolean }>(p => ({ type: p.$submit ? 'submit' : 'button', tabIndex: 0, }))``; expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); expect(TestRenderer.create(<Comp type="reset" />).toJSON()).toMatchSnapshot(); expect(TestRenderer.create(<Comp type="reset" tabIndex={-1} />).toJSON()).toMatchSnapshot(); }); it('should merge className', () => { const Comp = styled.div.attrs(() => ({ className: 'meow nya', }))``; expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); }); it('should merge className from folded attrs', () => { const Inner = styled.div.attrs({ className: 'foo' })``; const Comp = styled(Inner).attrs(() => ({ className: 'meow nya', }))``; expect(TestRenderer.create(<Comp className="something" />).toJSON()).toMatchInlineSnapshot(` <div className="sc-a sc-b foo meow nya something" /> `); }); it('should merge className even if its a function', () => { const Comp = styled.div.attrs<{ $purr?: boolean }>(p => ({ className: `meow ${p.$purr ? 'purr' : 'nya'}`, }))``; expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); expect(TestRenderer.create(<Comp $purr />).toJSON()).toMatchSnapshot(); }); it('should merge style', () => { const Comp = styled.div.attrs(() => ({ style: { color: 'red', background: 'blue' }, }))``; expect(TestRenderer.create(<Comp style={{ color: 'green', borderStyle: 'dotted' }} />).toJSON()) .toMatchInlineSnapshot(` <div className="sc-a" style={ { "background": "blue", "borderStyle": "dotted", "color": "red", } } /> `); }); it('should work with data and aria attributes', () => { const Comp = styled.div.attrs<DataAttributes>(() => ({ 'data-foo': 'bar', 'aria-label': 'A simple FooBar', }))``; expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); }); it('merge attrs', () => { const Comp = styled.button .attrs(() => ({ type: 'button', tabIndex: 0, })) .attrs(() => ({ type: 'submit', }))``; expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); }); it('merge attrs when inheriting SC', () => { const Parent = styled.button.attrs(() => ({ type: 'button', tabIndex: 0, }))``; const Child = styled(Parent).attrs(() => ({ type: 'submit', }))``; expect(TestRenderer.create(<Child />).toJSON()).toMatchSnapshot(); }); it('pass attrs to style block', () => { /* Would be a React Router Link in real life */ const Comp = styled.a.attrs<DataAttributes>(() => ({ href: '#', 'data-active-class-name': '--is-active', }))` color: blue; &.${props => props['data-active-class-name']} { color: red; } `; expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: blue; } .b.--is-active { color: red; }" `); }); it('should pass through children as a normal prop', () => { const Comp = styled.div.attrs(() => ({ children: 'Probably a bad idea', }))``; expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); }); it('should pass through complex children as well', () => { const Comp = styled.div.attrs(() => ({ children: <span>Probably a bad idea</span>, }))``; expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); }); it('should override children of course', () => { const Comp = styled.div.attrs(() => ({ children: <span>Amazing</span>, }))``; expect(TestRenderer.create(<Comp>Something else</Comp>).toJSON()).toMatchSnapshot(); }); it('should shallow merge "style" prop + attr instead of overwriting', () => { const Paragraph = styled.p.attrs<{ $fontScale?: number }>(p => ({ style: { ...p.style, fontSize: `${p.$fontScale}em`, }, }))<{ $fontScale: number }>` background: red; `; class Text extends React.Component< Partial<React.ComponentProps<typeof Paragraph>>, { fontScale: number } > { state = { // Assume that will be changed automatically // according to the dimensions of the container fontScale: 4, }; render() { return ( <Paragraph $fontScale={this.state.fontScale} {...this.props}> {this.props.children} </Paragraph> ); } } const BlueText = styled(Text).attrs(() => ({ style: { color: 'blue', }, }))` background: blue; `; const rendered = TestRenderer.create(<BlueText>Hello</BlueText>); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".d { background: red; } .c { background: blue; }" `); expect(rendered.toJSON()).toMatchInlineSnapshot(` <p className="sc-a d sc-b c" style={ { "color": "blue", "fontSize": "4em", } } > Hello </p> `); }); it('does not pass transient props to HTML element', () => { type CompProps = { $textColor: CSS.Properties['color'] }; const Comp = styled.div<CompProps>` color: ${props => props.$textColor}; `; const StyledComp = styled(Comp).attrs<Partial<CompProps>>(() => ({ $textColor: 'red', }))``; expect(TestRenderer.create(<StyledComp />).toJSON()).toMatchSnapshot(); }); it('should apply given "as" prop to the progressive type', () => { const Comp = styled.div.attrs({ as: 'video' as const })``; expect(TestRenderer.create(<Comp loop />).toJSON()).toMatchSnapshot(); }); });
3,059
0
petrpan-code/styled-components/styled-components/packages/styled-components/src
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/basic.test.tsx
import React, { Component, CSSProperties, StrictMode } from 'react'; import { findDOMNode } from 'react-dom'; import { findRenderedComponentWithType, renderIntoDocument } from 'react-dom/test-utils'; import TestRenderer from 'react-test-renderer'; import { find } from '../../test-utils'; import { AnyComponent } from '../types'; import hoist from '../utils/hoist'; import { getRenderedCSS, resetStyled } from './utils'; let styled: ReturnType<typeof resetStyled>; describe('basic', () => { /** * Make sure the setup is the same for every test */ beforeEach(() => { styled = resetStyled(); }); it('should not throw an error when called with a valid element', () => { expect(() => styled.div``).not.toThrowError(); const FunctionalComponent = () => <div />; class ClassComponent extends Component<any, any> { render() { return <div />; } } const validComps = ['div' as const, FunctionalComponent, ClassComponent]; validComps.forEach(comp => { expect(() => { const Comp = styled(comp)``; TestRenderer.create(<Comp />); }).not.toThrowError(); }); }); it('should not inject anything by default', () => { styled.div``; expect(getRenderedCSS()).toMatchInlineSnapshot(`""`); }); it('should inject styles', () => { const Comp = styled.div` color: blue; `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: blue; }" `); }); it("should inject only once for a styled component, no matter how often it's mounted", () => { const Comp = styled.div` color: blue; `; TestRenderer.create(<Comp />); TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: blue; }" `); }); it('should inject two different styles if the same component is mounted with different props and css', () => { const Comp = styled.div<{ $variant: 'text' | 'background' }>` color: ${props => props.$variant == 'text' && 'red'}; background-color: ${props => props.$variant == 'background' && 'red'}; `; TestRenderer.create(<Comp $variant="text" />); TestRenderer.create(<Comp $variant="background" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; } .c { background-color: red; }" `); }); it('Should have the correct styled(component) displayName', () => { const CompWithoutName = () => (() => <div />) as React.FC<any>; const StyledTag = styled.div``; expect(StyledTag.displayName).toBe('styled.div'); const CompWithName: React.FC<any> = () => <div />; CompWithName.displayName = undefined; const StyledCompWithName = styled(CompWithName)``; expect(StyledCompWithName.displayName).toBe('Styled(CompWithName)'); const CompWithDisplayName = CompWithoutName(); CompWithDisplayName.displayName = 'displayName'; const StyledCompWithDisplayName = styled(CompWithDisplayName)``; expect(StyledCompWithDisplayName.displayName).toBe('Styled(displayName)'); const CompWithBoth = () => <div />; CompWithBoth.displayName = 'displayName'; const StyledCompWithBoth = styled(CompWithBoth)``; expect(StyledCompWithBoth.displayName).toBe('Styled(displayName)'); const CompWithNothing = CompWithoutName(); CompWithNothing.displayName = undefined; const StyledCompWithNothing = styled(CompWithNothing)``; expect(StyledCompWithNothing.displayName).toBe('Styled(Component)'); }); it('should allow you to pass in style objects', () => { const Comp = styled.div({ color: 'blue', }); TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: blue; }" `); }); it('should allow you to pass in style object with a function', () => { const Comp = styled.div({ color: ({ color }) => color }); TestRenderer.create(<Comp color="blue" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: blue; }" `); }); it('should allow you to pass in style nested object', () => { const Comp = styled.div({ span: { small: { color: 'blue', fontFamily: 'sans-serif', }, }, }); TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b span small { color: blue; font-family: sans-serif; }" `); }); it('should allow you to pass in style nested object with a function', () => { const Comp = styled.div<{ color?: string }>({ span: { small: { color: ({ color }) => color, fontFamily: 'sans-serif', }, }, }); TestRenderer.create(<Comp color="red" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b span small { color: red; font-family: sans-serif; }" `); }); it('should allow you to pass in a function returning a style object', () => { const Comp = styled.div<{ color: Exclude<CSSProperties['color'], undefined> }>(({ color }) => ({ color, })); TestRenderer.create(<Comp color="blue" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: blue; }" `); }); it('emits the correct selector when a StyledComponent is interpolated into a template string', () => { const Comp = styled.div` color: red; `; expect(`${Comp}`).toBe(`.${Comp.styledComponentId}`); }); it('works with the React 16.6 "memo" API', () => { const Comp = React.memo(props => <div {...props} />); const StyledComp = styled(Comp)` color: red; `; TestRenderer.create(<StyledComp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; }" `); }); it('does not filter outs custom props for uppercased string-like components', () => { const Comp = styled('Comp')<{ customProp: string }>` color: red; `; const wrapper = TestRenderer.create(<Comp customProp="abc" />); expect(wrapper.root.findByType(Comp).props.customProp).toBe('abc'); }); it('creates a proper displayName for uppercased string-like components', () => { const Comp = styled('Comp')` color: red; `; expect(Comp.displayName).toBe('Styled(Comp)'); }); it('works with custom elements (use class instead of className)', () => { const Comp = styled('custom-element')` color: red; `; expect(TestRenderer.create(<Comp />).toJSON()).toMatchInlineSnapshot(` <custom-element class="sc-a b" /> `); }); describe('jsdom tests', () => { class InnerComponent extends Component<any, any> { render() { return <div {...this.props} />; } } it('should pass the full className to the wrapped child', () => { const OuterComponent = styled(InnerComponent)``; class Wrapper extends Component<any, any> { render() { return <OuterComponent className="test" />; } } const wrapper = TestRenderer.create(<Wrapper />); expect(wrapper.root.findByType(InnerComponent).props.className).toBe('sc-a test'); }); it('should pass the ref to the component', () => { const Comp = styled.div``; class Wrapper extends Component<any, any> { testRef = React.createRef<HTMLDivElement>(); render() { return ( <div> <Comp ref={this.testRef} /> </div> ); } } const wrapper = renderIntoDocument<any, Wrapper>(<Wrapper />); const component = find(findDOMNode(wrapper) as Element, Comp); expect(wrapper.testRef.current).toBe(component); }); it('should pass the ref to the wrapped styled component', () => { class Inner extends React.Component { render() { return <div {...this.props} />; } } const Outer = styled(Inner)``; class Wrapper extends Component<any, any> { testRef = React.createRef<InstanceType<typeof Inner>>(); render() { return ( <div> <Outer ref={this.testRef} /> </div> ); } } const wrapper = renderIntoDocument<any, Wrapper>(<Wrapper />); const innerComponent = findRenderedComponentWithType(wrapper, Inner); expect(wrapper.testRef.current).toBe(innerComponent); }); it('should respect the order of StyledComponent creation for CSS ordering', () => { const FirstComponent = styled.div` color: red; `; const SecondComponent = styled.div` color: blue; `; // NOTE: We're mounting second before first and check if we're breaking their order TestRenderer.create(<SecondComponent />); TestRenderer.create(<FirstComponent />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".d { color: red; } .c { color: blue; }" `); }); it('handle media at-rules inside style rules', () => { const Comp = styled.div` > * { @media (min-width: 500px) { color: pink; } } `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "@media (min-width:500px) { .b > * { color: pink; } }" `); }); it('should handle container queries inside style rules', () => { const Comp = styled.div` background: blue; container-type: inline-size; @container (width > 30px) { background: red; } `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { background: blue; container-type: inline-size; } @container (width > 30px) { .b { background: red; } }" `); }); it('should hoist non-react static properties on styled primitives', () => { const Inner = styled.div<{}, { foo: string }>``; Inner.foo = 'bar'; const Outer = styled(Inner)``; expect(Outer).toHaveProperty('foo', 'bar'); }); it('should hoist non-react static properties on wrapped components', () => { const Inner = styled('div')<{}, { foo: string }>``; Inner.foo = 'bar'; const Outer = styled(Inner)``; expect(Outer).toHaveProperty('foo', 'bar'); }); it('should not hoist styled component statics', () => { const Inner = styled.div``; const Outer = styled(Inner)``; expect(Outer.styledComponentId).not.toBe(Inner.styledComponentId); expect(Outer.componentStyle).not.toEqual(Inner.componentStyle); }); it('should not fold components if there is an interim HOC', () => { function withSomething(WrappedComponent: AnyComponent) { const WithSomething: React.FC<any> = props => { return <WrappedComponent {...props} />; }; hoist(WithSomething, WrappedComponent); return WithSomething; } const Inner = withSomething(styled.div` color: red; `); const Outer = styled(Inner)` color: green; `; const rendered = TestRenderer.create(<Outer />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".d { color: red; } .c { color: green; }" `); expect(rendered.toJSON()).toMatchInlineSnapshot(` <div className="sc-a d sc-b c" /> `); }); it('folds defaultProps', () => { const Inner = styled.div``; Inner.defaultProps = { theme: { fontSize: 12, }, style: { background: 'blue', textAlign: 'center', }, }; const Outer = styled(Inner)``; Outer.defaultProps = { theme: { fontSize: 16, }, style: { background: 'silver', }, }; expect(Outer.defaultProps).toMatchInlineSnapshot(` { "style": { "background": "silver", "textAlign": "center", }, "theme": { "fontSize": 16, }, } `); }); it('generates unique classnames when not using babel', () => { const Named1 = styled.div.withConfig({ displayName: 'Name' })` color: blue; `; const Named2 = styled.div.withConfig({ displayName: 'Name' })` color: red; `; expect(Named1.styledComponentId).not.toBe(Named2.styledComponentId); }); it('honors a passed componentId', () => { const Named1 = styled.div.withConfig({ componentId: 'foo', displayName: 'Name', })` color: blue; `; const Named2 = styled.div.withConfig({ componentId: 'bar', displayName: 'Name', })` color: red; `; expect(Named1.styledComponentId).toBe('Name-foo'); expect(Named2.styledComponentId).toBe('Name-bar'); }); // this no longer is possible in React 16.6 because // of the deprecation of findDOMNode; need to find an alternative it('should work in StrictMode without warnings', () => { const spy = jest.spyOn(console, 'error').mockImplementation(() => {}); const Comp = styled.div``; TestRenderer.create( <StrictMode> <Comp /> </StrictMode> ); expect(spy).not.toHaveBeenCalled(); }); }); describe('warnings', () => { beforeEach(() => { jest.spyOn(console, 'warn').mockImplementation(() => {}); }); it('does not warn for innerRef if using a custom component', () => { const InnerComp: React.FC<any> = props => <div {...props} />; const Comp = styled(InnerComp)``; const ref = React.createRef(); TestRenderer.create(<Comp innerRef={ref} />); expect(console.warn).not.toHaveBeenCalled(); }); it('does not warn if the className is consumed by a deeper child', () => { const Inner: React.FC<any> = ({ className }) => ( <div> <span className={className} /> </div> ); const Comp = styled(Inner)` color: red; `; renderIntoDocument( <div> <Comp /> </div> ); expect(console.warn).not.toHaveBeenCalled(); }); }); describe('production mode', () => { let originalEnv: string | undefined; beforeEach(() => { originalEnv = process.env.NODE_ENV; process.env.NODE_ENV = 'production'; }); afterEach(() => { process.env.NODE_ENV = originalEnv; }); it('should inject two different styles if the same compnoent is mounted with different props and css', () => { const Comp = styled.div<{ $variant: 'text' | 'background' }>` color: ${props => props.$variant == 'text' && 'red'}; background-color: ${props => props.$variant == 'background' && 'red'}; `; TestRenderer.create(<Comp $variant="text" />); TestRenderer.create(<Comp $variant="background" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; } .c { background-color: red; }" `); }); }); });
3,060
0
petrpan-code/styled-components/styled-components/packages/styled-components/src
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/constants.test.tsx
import { SC_ATTR as DEFAULT_SC_ATTR } from '../constants'; import { expectCSSMatches } from './utils'; declare global { namespace NodeJS { export interface ProcessEnv { REACT_APP_SC_DISABLE_SPEEDY?: boolean | string; SC_DISABLE_SPEEDY?: boolean | string; } } interface Window { REACT_APP_SC_DISABLE_SPEEDY?: boolean | string; SC_DISABLE_SPEEDY?: boolean | string; } } describe('constants', () => { afterEach(() => { jest.resetModules(); }); describe('SC_ATTR', () => { function renderAndExpect(expectedAttr: string) { const React = require('react'); const TestRenderer = require('react-test-renderer'); const { SC_ATTR } = require('../constants'); const styled = require('./utils').resetStyled(); const Comp = styled.div` color: blue; `; TestRenderer.create(<Comp />); expectCSSMatches('.b { color:blue; }'); expect(SC_ATTR).toEqual(expectedAttr); expect(document.head.querySelectorAll(`style[${SC_ATTR}]`)).toHaveLength(1); } it('should work with default SC_ATTR', () => { renderAndExpect(DEFAULT_SC_ATTR); }); it('should work with custom SC_ATTR', () => { const CUSTOM_SC_ATTR = 'data-custom-styled-components'; process.env.SC_ATTR = CUSTOM_SC_ATTR; jest.resetModules(); renderAndExpect(CUSTOM_SC_ATTR); delete process.env.SC_ATTR; }); it('should work with REACT_APP_SC_ATTR', () => { const REACT_APP_CUSTOM_SC_ATTR = 'data-custom-react_app-styled-components'; process.env.REACT_APP_SC_ATTR = REACT_APP_CUSTOM_SC_ATTR; jest.resetModules(); renderAndExpect(REACT_APP_CUSTOM_SC_ATTR); delete process.env.REACT_APP_SC_ATTR; }); }); describe('DISABLE_SPEEDY', () => { function renderAndExpect(expectedDisableSpeedy: boolean, expectedCss: string) { const React = require('react'); const TestRenderer = require('react-test-renderer'); const { DISABLE_SPEEDY } = require('../constants'); const styled = require('./utils').resetStyled(); const Comp = styled.div` color: blue; `; TestRenderer.create(<Comp />); expect(DISABLE_SPEEDY).toEqual(expectedDisableSpeedy); expectCSSMatches(expectedCss); } beforeEach(() => { process.env.NODE_ENV = 'production'; }); afterEach(() => { process.env.NODE_ENV = 'test'; delete process.env.DISABLE_SPEEDY; delete window.SC_DISABLE_SPEEDY; }); it('should be false in production NODE_ENV when SC_DISABLE_SPEEDY is not set', () => { renderAndExpect(false, ''); }); it('should be false in production NODE_ENV when window.SC_DISABLE_SPEEDY is set to false', () => { window.SC_DISABLE_SPEEDY = false; renderAndExpect(false, ''); }); it('should be false in development NODE_ENV when window.SC_DISABLE_SPEEDY is set to false', () => { process.env.NODE_ENV = 'development'; window.SC_DISABLE_SPEEDY = false; renderAndExpect(false, ''); }); it('should be false in production NODE_ENV when window.SC_DISABLE_SPEEDY is set to truthy value', () => { window.SC_DISABLE_SPEEDY = 'true'; renderAndExpect(false, ''); }); it('should be true in production NODE_ENV when window.SC_DISABLE_SPEEDY is set to true', () => { window.SC_DISABLE_SPEEDY = true; renderAndExpect(true, '.b { color:blue; }'); }); it('should be true in test NODE_ENV', () => { process.env.NODE_ENV = 'test'; renderAndExpect(true, '.b { color:blue; }'); }); it('should be true in development NODE_ENV', () => { process.env.NODE_ENV = 'development'; renderAndExpect(true, '.b { color:blue; }'); }); it('should work with SC_DISABLE_SPEEDY environment variable', () => { process.env.SC_DISABLE_SPEEDY = true; renderAndExpect(true, '.b { color:blue; }'); delete process.env.SC_DISABLE_SPEEDY; }); it('should work with SC_DISABLE_SPEEDY environment variable when set to `false` in development NODE_ENV', () => { process.env.NODE_ENV = 'development'; process.env.SC_DISABLE_SPEEDY = false; renderAndExpect(false, ''); delete process.env.SC_DISABLE_SPEEDY; }); it('should work with SC_DISABLE_SPEEDY environment variable when set to "false" in development NODE_ENV', () => { process.env.NODE_ENV = 'development'; process.env.SC_DISABLE_SPEEDY = 'false'; renderAndExpect(false, ''); delete process.env.SC_DISABLE_SPEEDY; }); it('should work with REACT_APP_SC_DISABLE_SPEEDY environment variable', () => { process.env.REACT_APP_SC_DISABLE_SPEEDY = true; renderAndExpect(true, '.b { color:blue; }'); delete process.env.REACT_APP_SC_DISABLE_SPEEDY; }); it('should work with REACT_APP_SC_DISABLE_SPEEDY environment variable when set to `false` in development NODE_ENV', () => { process.env.NODE_ENV = 'development'; process.env.REACT_APP_SC_DISABLE_SPEEDY = false; renderAndExpect(false, ''); delete process.env.REACT_APP_SC_DISABLE_SPEEDY; }); it('should work with REACT_APP_SC_DISABLE_SPEEDY environment variable when set to "false" in development NODE_ENV', () => { process.env.NODE_ENV = 'development'; process.env.REACT_APP_SC_DISABLE_SPEEDY = 'false'; renderAndExpect(false, ''); delete process.env.REACT_APP_SC_DISABLE_SPEEDY; }); }); });
3,061
0
petrpan-code/styled-components/styled-components/packages/styled-components/src
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/css.test.tsx
import React from 'react'; import TestRenderer from 'react-test-renderer'; import { getRenderedCSS, resetStyled } from './utils'; // Disable isStaticRules optimisation since we're not // testing for ComponentStyle specifics here jest.mock('../utils/isStaticRules', () => () => false); let styled: ReturnType<typeof resetStyled>; describe('css features', () => { beforeEach(() => { styled = resetStyled(); }); it('should add vendor prefixes in the right order', () => { const Comp = styled.div` transition: opacity 0.3s; `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { transition: opacity 0.3s; }" `); }); it('should add vendor prefixes for display', () => { const Comp = styled.div` display: flex; flex-direction: column; align-items: center; `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { display: flex; flex-direction: column; align-items: center; }" `); }); it('should generate styles for nested media queries', () => { const Comp = styled.div` @media (min-width: 10px) { @media (min-height: 20px) { color: red; } } `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "@media (min-width:10px) { @media (min-height:20px) { .b { color: red; } } }" `); }); it('should pass through custom properties', () => { const Comp = styled.div` --custom-prop: some-val; `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { --custom-prop: some-val; }" `); }); });
3,062
0
petrpan-code/styled-components/styled-components/packages/styled-components/src
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/expanded-api.test.tsx
import React from 'react'; import TestRenderer from 'react-test-renderer'; import { getRenderedCSS, resetStyled } from './utils'; // Disable isStaticRules optimisation since we're not // testing for ComponentStyle specifics here jest.mock('../utils/isStaticRules', () => () => false); let styled: ReturnType<typeof resetStyled>; describe('expanded api', () => { /** * Make sure the setup is the same for every test */ beforeEach(() => { styled = resetStyled(); }); describe('displayName', () => { it('should be auto-generated if none passed', () => { const Comp = styled.div``; expect(Comp.displayName).toBe('styled.div'); }); it('should be attached if supplied', () => { const Comp = styled.div.withConfig({ displayName: 'Comp' })``; expect(Comp.displayName).toBe('Comp'); }); }); describe('componentId', () => { it('should be generated as "sc" + hash', () => { const Comp = styled.div``; const Comp2 = styled.div``; expect(Comp.styledComponentId).toBe('sc-a'); expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); expect(Comp2.styledComponentId).toBe('sc-b'); expect(TestRenderer.create(<Comp2 />)).toMatchSnapshot(); }); it('should be generated from displayName + hash', () => { const Comp = styled.div.withConfig({ displayName: 'Comp' })``; const Comp2 = styled.div.withConfig({ displayName: 'Comp2' })``; expect(Comp.styledComponentId).toBe('Comp-a'); expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); expect(Comp2.styledComponentId).toBe('Comp2-b'); expect(TestRenderer.create(<Comp2 />)).toMatchSnapshot(); }); it('should be attached if passed in', () => { const Comp = styled.div.withConfig({ componentId: 'LOLOMG' })``; const Comp2 = styled.div.withConfig({ componentId: 'OMGLOL' })``; expect(Comp.styledComponentId).toBe('LOLOMG'); expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); expect(Comp2.styledComponentId).toBe('OMGLOL'); expect(TestRenderer.create(<Comp2 />)).toMatchSnapshot(); }); it('should be combined with displayName if both passed in', () => { const Comp = styled.div.withConfig({ displayName: 'Comp', componentId: 'LOLOMG', })``; const Comp2 = styled.div.withConfig({ displayName: 'Comp2', componentId: 'OMGLOL', })``; expect(Comp.styledComponentId).toBe('Comp-LOLOMG'); expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); expect(Comp2.styledComponentId).toBe('Comp2-OMGLOL'); expect(TestRenderer.create(<Comp2 />).toJSON()).toMatchSnapshot(); }); }); describe('chaining', () => { it('should merge the options strings', () => { const Comp = styled.div .withConfig({ componentId: 'id-1' }) .withConfig({ displayName: 'dn-2' })``; expect(Comp.displayName).toBe('dn-2'); expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); }); it('should keep the last value passed in when merging', () => { const Comp = styled.div .withConfig({ displayName: 'dn-2', componentId: 'id-3' }) .withConfig({ displayName: 'dn-5', componentId: 'id-4' })``; expect(Comp.displayName).toBe('dn-5'); expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); }); }); describe('"as" prop', () => { it('changes the rendered element type', () => { const Comp = styled.div` color: red; `; expect(TestRenderer.create(<Comp as="span" />).toJSON()).toMatchSnapshot(); }); it('changes the rendered element type when used with attrs', () => { const Comp = styled.div.attrs(() => ({ as: 'header', }))` color: red; `; expect(TestRenderer.create(<Comp />).toJSON()).toMatchSnapshot(); }); it('prefers attrs over props', () => { const Comp = styled.div.attrs(() => ({ as: 'header', }))` color: red; `; expect(TestRenderer.create(<Comp as="span" />).toJSON()).toMatchInlineSnapshot(` <header className="sc-a b" /> `); }); it('works with custom components', () => { const Override: React.FC<any> = props => <figure {...props} />; const Comp = styled.div` color: red; `; expect(TestRenderer.create(<Comp as={Override} />).toJSON()).toMatchSnapshot(); }); it('transfers all styles that have been applied', () => { const Comp = styled.div` background: blue; color: red; `; const Comp2 = styled(Comp)` color: green; `; const Comp3 = styled(Comp2)` text-align: center; `; expect(Comp.displayName).toMatchInlineSnapshot(`"styled.div"`); expect(Comp2.displayName).toMatchInlineSnapshot(`"Styled(styled.div)"`); expect(Comp3.displayName).toMatchInlineSnapshot(`"Styled(Styled(styled.div))"`); expect(TestRenderer.create(<Comp />).toJSON()).toMatchInlineSnapshot(` <div className="sc-a d" /> `); expect(TestRenderer.create(<Comp2 />).toJSON()).toMatchInlineSnapshot(` <div className="sc-a sc-b d e" /> `); expect(TestRenderer.create(<Comp3 as="span" />).toJSON()).toMatchInlineSnapshot(` <span className="sc-a sc-b sc-c d e f" /> `); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".d { background: blue; color: red; } .e { color: green; } .f { text-align: center; }" `); }); it('"as" prop signature should inform rendered JSX if provided', () => { const X = styled.div<{ as?: 'div' | 'button' }>``; const StyledX = styled(X)``; TestRenderer.create( <> <X // @ts-expect-error invalid input test as="section" /> <StyledX // @ts-expect-error invalid input test as="section" /> </> ); }); }); });
3,064
0
petrpan-code/styled-components/styled-components/packages/styled-components/src
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/overriding.test.tsx
import React from 'react'; import TestRenderer from 'react-test-renderer'; import { AnyComponent } from '../types'; import { getRenderedCSS, resetStyled } from './utils'; // Disable isStaticRules optimisation since we're not // testing for ComponentStyle specifics here jest.mock('../utils/isStaticRules', () => () => false); let styled: ReturnType<typeof resetStyled>; describe('extending', () => { /** * Make sure the setup is the same for every test */ beforeEach(() => { styled = resetStyled(); }); it('should let you use another component in a css rule', () => { const Inner = styled.div` color: blue; font-weight: light; `; const Outer = styled.div` padding: 1rem; > ${Inner} { font-weight: bold; } `; TestRenderer.create(<Inner />); TestRenderer.create(<Outer />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".c { color: blue; font-weight: light; } .d { padding: 1rem; } .d > .sc-a { font-weight: bold; }" `); }); it('folded components should not duplicate styles', () => { const Inner = styled.div` color: blue; & + & { color: green; } `; const Outer = styled(Inner)` padding: 1rem; `; TestRenderer.create(<Inner />); const tree = TestRenderer.create(<Outer />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".c { color: blue; } .sc-a + .sc-a { color: green; } .d { padding: 1rem; }" `); // ensure both static classes are applied and dynamic classes are also present expect(tree.toJSON()).toMatchInlineSnapshot(` <div className="sc-a sc-b c d" /> `); }); describe('inheritance', () => { const setupParent = () => { const colors = { primary: 'red', secondary: 'blue', tertiary: 'green', }; const Parent = styled.h1<{ color?: keyof typeof colors }>` position: relative; color: ${props => colors[props.color!]}; `; return Parent; }; const addDefaultProps = (Parent: AnyComponent, Child: AnyComponent, Grandson: AnyComponent) => { Parent.defaultProps = { color: 'primary', }; Child.defaultProps = { color: 'secondary', }; Grandson.defaultProps = { color: 'tertiary', }; }; it('should override parents defaultProps', () => { const Parent = setupParent(); const Child = styled(Parent)``; const Grandson = styled(Child)``; addDefaultProps(Parent, Child, Grandson); TestRenderer.create(<Parent />); TestRenderer.create(<Child />); TestRenderer.create(<Grandson />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".d { position: relative; color: red; } .e { position: relative; color: blue; } .f { position: relative; color: green; }" `); }); describe('when overriding with another component', () => { it('should override parents defaultProps', () => { const Parent = setupParent(); const Child = styled(Parent).attrs({ as: 'h2' })``; const Grandson = styled(Child).attrs(() => ({ as: 'h3' }))``; addDefaultProps(Parent, Child, Grandson); TestRenderer.create(<Parent />); TestRenderer.create(<Child />); TestRenderer.create(<Grandson />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".d { position: relative; color: red; } .e { position: relative; color: blue; } .f { position: relative; color: green; }" `); }); it('should evaluate grandsons props', () => { const Parent = setupParent(); const Child = styled(Parent).attrs({ as: 'h2' })``; const Grandson = styled(Child).attrs(() => ({ as: 'h3' }))``; addDefaultProps(Parent, Child, Grandson); expect(TestRenderer.create(<Parent />).toJSON()).toMatchInlineSnapshot(` <h1 className="sc-a d" color="primary" /> `); expect(TestRenderer.create(<Child />).toJSON()).toMatchInlineSnapshot(` <h2 className="sc-a sc-b e" color="secondary" /> `); expect(TestRenderer.create(<Grandson color="primary" />).toJSON()).toMatchInlineSnapshot(` <h3 className="sc-a sc-b sc-c d" color="primary" /> `); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".d { position: relative; color: red; } .e { position: relative; color: blue; }" `); }); }); }); });
3,065
0
petrpan-code/styled-components/styled-components/packages/styled-components/src
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/props.test.tsx
import React, { Fragment } from 'react'; import TestRenderer from 'react-test-renderer'; import { getRenderedCSS, resetStyled } from './utils'; let styled: ReturnType<typeof resetStyled>; describe('props', () => { beforeEach(() => { styled = resetStyled(); }); it('should execute interpolations and fall back', () => { const Comp = styled.div<{ fg?: string }>` color: ${props => props.fg || 'black'}; `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: black; }" `); }); it('should execute interpolations and inject props', () => { const Comp = styled.div<{ fg: string }>` color: ${props => props.fg || 'black'}; `; TestRenderer.create(<Comp fg="red" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; }" `); }); it('should ignore non-0 falsy object interpolations', () => { const Comp = styled.div<{ fg: string }>` ${ // @ts-expect-error improper input () => ({ borderWidth: 0, colorA: null, colorB: false, colorC: undefined, colorD: '', }) }; `; TestRenderer.create(<Comp fg="red" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { border-width: 0; }" `); }); it('should filter out props prefixed with dollar sign (transient props)', () => { const Comp = styled((p: any) => <div {...p} />)<{ $fg?: string; fg?: string }>` color: ${props => props.$fg || 'black'}; `; expect( TestRenderer.create( <> <Comp $fg="red" /> <Comp fg="red" /> </> ).toJSON() ).toMatchInlineSnapshot(` [ <div className="sc-a b" />, <div className="sc-a c" fg="red" />, ] `); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; } .c { color: black; }" `); }); it('should forward the "as" prop if "forwardedAs" is used', () => { const Comp = ({ as: Component = 'div', ...props }) => <Component {...props} />; const Comp2 = styled(Comp)` background: red; `; expect(TestRenderer.create(<Comp2 forwardedAs="button" />).toJSON()).toMatchInlineSnapshot(` <button className="sc-a b" /> `); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { background: red; }" `); }); describe('shouldForwardProp', () => { // NB existing functionality (when `shouldForwardProp` is not set) is tested elsewhere it('allows for custom prop filtering for elements', () => { const Comp = styled('div').withConfig({ shouldForwardProp: prop => !['filterThis'].includes(prop), })<{ filterThis: string; passThru: string }>` color: red; `; const wrapper = TestRenderer.create(<Comp filterThis="abc" passThru="def" />); const { props } = wrapper.root.findByType('div'); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; }" `); expect(props.passThru).toBe('def'); expect(props.filterThis).toBeUndefined(); }); it('allows custom prop filtering for components', () => { const InnerComp = (props: JSX.IntrinsicElements['div']) => <div {...props} />; const Comp = styled(InnerComp).withConfig({ shouldForwardProp: prop => !['filterThis'].includes(prop), })<{ filterThis: string; passThru: string }>` color: red; `; const wrapper = TestRenderer.create(<Comp filterThis="abc" passThru="def" />); const { props } = wrapper.root.findByType('div'); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; }" `); expect(props.passThru).toBe('def'); expect(props.filterThis).toBeUndefined(); }); it('composes shouldForwardProp on composed styled components', () => { const StyledDiv = styled('div').withConfig({ shouldForwardProp: prop => prop === 'passThru', })<{ filterThis: boolean; passThru: boolean }>` color: red; `; const ComposedDiv = styled(StyledDiv).withConfig({ shouldForwardProp: () => true, })``; const wrapper = TestRenderer.create(<ComposedDiv filterThis passThru />); const { props } = wrapper.root.findByType('div'); expect(props.passThru).toBeDefined(); expect(props.filterThis).toBeUndefined(); }); it('should inherit shouldForwardProp for wrapped styled components', () => { const Div1 = styled('div').withConfig({ shouldForwardProp: prop => prop !== 'color', })<{ color: string }>` background-color: ${({ color }) => color}; `; const Div2 = styled(Div1)``; const wrapper = TestRenderer.create( <Fragment> <Div1 color="red" id="test-1" /> <Div2 color="green" id="test-2" /> </Fragment> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".c { background-color: red; } .d { background-color: green; }" `); expect(wrapper.toJSON()).toMatchSnapshot(); }); it('should filter out props when using "as" to a custom component', () => { const AsComp = (props: JSX.IntrinsicElements['div']) => <div {...props} />; const Comp = styled('div').withConfig({ shouldForwardProp: prop => !['filterThis'].includes(prop), })<{ filterThis: string; passThru: string }>` color: red; `; const wrapper = TestRenderer.create(<Comp as={AsComp} filterThis="abc" passThru="def" />); const { props } = wrapper.root.findByType(AsComp); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; }" `); expect(props.passThru).toBe('def'); expect(props.filterThis).toBeUndefined(); }); it('can set computed styles based on props that are being filtered out', () => { const AsComp = (props: JSX.IntrinsicElements['div']) => <div {...props} />; const Comp = styled('div').withConfig({ shouldForwardProp: prop => !['filterThis'].includes(prop), })<{ filterThis: string; passThru: string }>` color: ${props => (props.filterThis === 'abc' ? 'red' : undefined)}; `; const wrapper = TestRenderer.create(<Comp as={AsComp} filterThis="abc" passThru="def" />); const { props } = wrapper.root.findByType(AsComp); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; }" `); expect(props.passThru).toBe('def'); expect(props.filterThis).toBeUndefined(); }); it('should filter our props when using "as" to a different element', () => { const Comp = styled('div').withConfig({ shouldForwardProp: prop => !['filterThis'].includes(prop), })<{ filterThis: string; passThru: string }>` color: red; `; const wrapper = TestRenderer.create(<Comp as="a" filterThis="abc" passThru="def" />); const { props } = wrapper.root.findByType('a'); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; }" `); expect(props.passThru).toBe('def'); expect(props.filterThis).toBeUndefined(); }); it('passes the target element for use if desired', () => { const stub = jest.fn(); const Comp = styled('div').withConfig({ shouldForwardProp: stub, })<{ filterThis: string; passThru: string }>` color: red; `; TestRenderer.create(<Comp as="a" href="/foo" filterThis="abc" passThru="def" />); expect(stub).toHaveBeenCalledWith('filterThis', 'a'); expect(stub).toHaveBeenCalledWith('href', 'a'); }); it('warns in development mode when shouldForwardProp is not provided for an unknown prop', () => { let originalEnv = process.env.NODE_ENV; process.env.NODE_ENV = 'development'; jest.spyOn(console, 'warn').mockImplementation(() => {}); const Comp = styled('div')<{ filterThis: string }>` color: red; `; TestRenderer.create(<Comp as="a" href="/foo" filterThis="abc" />); expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('filterThis')); process.env.NODE_ENV = originalEnv; }); it('do not warn in development mode when shouldForwardProp is not provided for an unknown prop on React component', () => { let originalEnv = process.env.NODE_ENV; process.env.NODE_ENV = 'development'; jest.spyOn(console, 'warn').mockImplementation(() => {}); const Comp = styled(({ className, myLabel }: { className?: string; myLabel: string }) => ( <span className={className}>{myLabel}</span> ))` color: red; `; TestRenderer.create(<Comp myLabel="My label" />); expect(console.warn).not.toHaveBeenCalledWith(expect.stringContaining('myLabel')); expect(console.warn).toHaveBeenCalledTimes(0); process.env.NODE_ENV = originalEnv; }); }); });
3,066
0
petrpan-code/styled-components/styled-components/packages/styled-components/src
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/rehydration.test.tsx
import React from 'react'; import TestRenderer from 'react-test-renderer'; import { SC_ATTR, SC_ATTR_VERSION } from '../constants'; import { getRenderedCSS, rehydrateTestStyles, resetStyled, seedNextClassnames } from './utils'; declare const __VERSION__: string; /* NOTE: Sometimes we add an empty function interpolation into some styled-components to skip the static optimisation in ComponentStyle. This will look like this: ${() => ''} */ let styled: ReturnType<typeof resetStyled>; let createGlobalStyle: Awaited<typeof import('../constructors/createGlobalStyle')>['default']; let keyframes: Awaited<typeof import('../constructors/keyframes')>['default']; describe('rehydration', () => { /** * Make sure the setup is the same for every test */ beforeEach(() => { createGlobalStyle = require('../constructors/createGlobalStyle'); keyframes = require('../constructors/keyframes'); styled = resetStyled(); }); describe('with existing styled components', () => { beforeEach(() => { document.head.innerHTML = ` <style ${SC_ATTR} ${SC_ATTR_VERSION}="${__VERSION__}"> .b { color: red; }/*!sc*/ ${SC_ATTR}.g1[id="TWO"]{content: "b,"}/*!sc*/ </style> `; rehydrateTestStyles(); }); it('should preserve the styles', () => { expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; }" `); }); it('should append a new component like normal', () => { const Comp = styled.div.withConfig({ componentId: 'ONE' })` color: blue; ${() => ''} `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; } .a { color: blue; }" `); }); it('should reuse a componentId', () => { const A = styled.div.withConfig({ componentId: 'ONE' })` color: blue; ${() => ''} `; TestRenderer.create(<A />); const B = styled.div.withConfig({ componentId: 'TWO' })``; TestRenderer.create(<B />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; } .a { color: blue; }" `); }); it('should reuse a componentId and generated class', () => { const A = styled.div.withConfig({ componentId: 'ONE' })` color: blue; ${() => ''} `; TestRenderer.create(<A />); const B = styled.div.withConfig({ componentId: 'TWO' })` color: red; ${() => ''} `; TestRenderer.create(<B />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; } .a { color: blue; }" `); }); it('should reuse a componentId and inject new classes', () => { const A = styled.div.withConfig({ componentId: 'ONE' })` color: blue; ${() => ''} `; TestRenderer.create(<A />); const B = styled.div.withConfig({ componentId: 'TWO' })` color: ${() => 'red'}; `; TestRenderer.create(<B />); const C = styled.div.withConfig({ componentId: 'TWO' })` color: ${() => 'green'}; `; TestRenderer.create(<C />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; } .c { color: green; } .a { color: blue; }" `); }); }); describe('with styled components with props', () => { beforeEach(() => { /* Hash 1323611362 is based on name TWO and contents color: red. * Change either and this will break. */ document.head.innerHTML = ` <style ${SC_ATTR} ${SC_ATTR_VERSION}="${__VERSION__}"> .a { color: blue; }/*!sc*/ ${SC_ATTR}.g1[id="ONE"]{content: "a,"}/*!sc*/ .b { color: red; }/*!sc*/ ${SC_ATTR}.g2[id="TWO"]{content: "b,"}/*!sc*/ </style> `; rehydrateTestStyles(); }); it('should preserve the styles', () => { expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { color: blue; } .b { color: red; }" `); }); it('should not inject new styles for a component already rendered', () => { const Comp = styled.div.withConfig({ componentId: 'ONE' })` color: ${props => props.color}; `; TestRenderer.create(<Comp color="blue" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { color: blue; } .b { color: red; }" `); }); it('should inject new styles for a new computed style of a component', () => { seedNextClassnames(['x']); const Comp = styled.div.withConfig({ componentId: 'ONE' })` color: ${props => props.color}; `; TestRenderer.create(<Comp color="green" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { color: blue; } .x { color: green; } .b { color: red; }" `); }); }); describe('with inline styles that werent rendered by us', () => { beforeEach(() => { /* Same css as before, but without the data attributes we ignore it */ document.head.innerHTML = ` <style> .b { color: red; }/*!sc*/ ${SC_ATTR}.g2[id="TWO"]{content: "b,"}/*!sc*/ </style> `; rehydrateTestStyles(); }); it('should leave the existing styles there', () => { expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; } data-styled.g2[id="TWO"] { content: "b," }" `); }); }); describe('with global styles', () => { beforeEach(() => { /* Adding a non-local stylesheet with a hash 557410406 which is * derived from "body { background: papayawhip; }" so be careful * changing it. */ document.head.innerHTML = ` <style ${SC_ATTR} ${SC_ATTR_VERSION}="${__VERSION__}"> body { background: papayawhip; }/*!sc*/ ${SC_ATTR}.g1[id="sc-global-557410406"]{content: "sc-global-557410406,"}/*!sc*/ </style> <style ${SC_ATTR} ${SC_ATTR_VERSION}="${__VERSION__}"> .a { color: red; }/*!sc*/ ${SC_ATTR}.g2[id="TWO"]{content: "a,"}/*!sc*/ </style> `; rehydrateTestStyles(); }); it('should leave the existing styles there', () => { expect(getRenderedCSS()).toMatchInlineSnapshot(` "body { background: papayawhip; } .a { color: red; }" `); }); it('should inject new global styles at the end', () => { const Component = createGlobalStyle` body { color: tomato; } `; TestRenderer.create(<Component />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "body { background: papayawhip; } .a { color: red; } body { color: tomato; }" `); }); it('should interleave global and local styles', () => { const Component = createGlobalStyle` body { color: tomato; } `; const A = styled.div.withConfig({ componentId: 'ONE' })` color: blue; ${() => ''} `; TestRenderer.create(<Component />); TestRenderer.create(<A />); // although `<Component />` is rendered before `<A />`, the global style isn't registered until render time // compared to typical component styles which are registered at creation time expect(getRenderedCSS()).toMatchInlineSnapshot(` "body { background: papayawhip; } .a { color: red; } body { color: tomato; } .b { color: blue; }" `); }); }); describe('with all styles already rendered', () => { beforeEach(() => { document.head.innerHTML = ` <style ${SC_ATTR} ${SC_ATTR_VERSION}="${__VERSION__}"> html { font-size: 16px; }/*!sc*/ ${SC_ATTR}.g1[id="sc-global-a1"]{content: "sc-global-a1,"}/*!sc*/ body { background: papayawhip; }/*!sc*/ ${SC_ATTR}.g2[id="sc-global-b1"]{content: "sc-global-b1,"}/*!sc*/ .c { color: blue; }/*!sc*/ ${SC_ATTR}.g3[id="ONE"]{content: "c,"}/*!sc*/ .d { color: red; }/*!sc*/ ${SC_ATTR}.g4[id="TWO"]{content: "d,"}/*!sc*/ </style> `; rehydrateTestStyles(); }); it('should not touch existing styles', () => { expect(getRenderedCSS()).toMatchInlineSnapshot(` "html { font-size: 16px; } body { background: papayawhip; } .c { color: blue; } .d { color: red; }" `); }); it('should not change styles if rendered in the same order they were created with', () => { const Component1 = createGlobalStyle` html { font-size: 16px; } `; TestRenderer.create(<Component1 />); const Component2 = createGlobalStyle` body { background: papayawhip; } `; TestRenderer.create(<Component2 />); const A = styled.div.withConfig({ componentId: 'ONE' })` color: blue; `; TestRenderer.create(<A />); const B = styled.div.withConfig({ componentId: 'TWO' })` color: red; `; TestRenderer.create(<B />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "html { font-size: 16px; } body { background: papayawhip; } .c { color: blue; } .d { color: red; }" `); }); it('should still not change styles if rendered in a different order', () => { seedNextClassnames(['d', 'a', 'b', 'c']); const B = styled.div.withConfig({ componentId: 'TWO' })` color: red; `; TestRenderer.create(<B />); const Component1 = createGlobalStyle` html { font-size: 16px; } `; TestRenderer.create(<Component1 />); const Component2 = createGlobalStyle` body { background: papayawhip; } `; TestRenderer.create(<Component2 />); const A = styled.div.withConfig({ componentId: 'ONE' })` color: blue; `; TestRenderer.create(<A />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "html { font-size: 16px; } body { background: papayawhip; } .c { color: blue; } .d { color: red; }" `); }); }); describe('with keyframes', () => { beforeEach(() => { document.head.innerHTML = ` <style ${SC_ATTR} ${SC_ATTR_VERSION}="${__VERSION__}"> @-webkit-keyframes keyframe_880 {from {opacity: 0;}}@keyframes keyframe_880 {from {opacity: 0;}}/*!sc*/ ${SC_ATTR}.g1[id="sc-keyframes-keyframe_880"]{content: "keyframe_880,"}/*!sc*/ </style> `; rehydrateTestStyles(); }); it('should not touch existing styles', () => { expect(getRenderedCSS()).toMatchInlineSnapshot(` "@-webkit-keyframes keyframe_880 { from { opacity: 0; } } @keyframes keyframe_880 { from { opacity: 0; } }" `); }); it('should not regenerate keyframes', () => { seedNextClassnames(['keyframe_880']); const fadeIn = keyframes` from { opacity: 0; } `; const A = styled.div` animation: ${fadeIn} 1s both; ${() => ''} `; TestRenderer.create(<A />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "@-webkit-keyframes keyframe_880 { from { opacity: 0; } } @keyframes keyframe_880 { from { opacity: 0; } } .b { animation: keyframe_880 1s both; }" `); }); it('should still inject new keyframes', () => { seedNextClassnames(['keyframe_144']); const fadeOut = keyframes` from { opacity: 1; } `; const A = styled.div` animation: ${fadeOut} 1s both; ${() => ''} `; TestRenderer.create(<A />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "@-webkit-keyframes keyframe_880 { from { opacity: 0; } } @keyframes keyframe_880 { from { opacity: 0; } } .b { animation: keyframe_144 1s both; } @keyframes keyframe_144 { from { opacity: 1; } }" `); }); it('should pass the keyframes name along as well', () => { seedNextClassnames(['keyframe_880', 'keyframe_144']); const fadeIn = keyframes` from { opacity: 0; } `; const fadeOut = keyframes` from { opacity: 1; } `; const A = styled.div` animation: ${fadeIn} 1s both; ${() => ''} `; const B = styled.div` animation: ${fadeOut} 1s both; ${() => ''} `; /* Purposely rendering out of order to make sure the output looks right */ TestRenderer.create(<B />); TestRenderer.create(<A />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "@-webkit-keyframes keyframe_880 { from { opacity: 0; } } @keyframes keyframe_880 { from { opacity: 0; } } .d { animation: keyframe_880 1s both; } .c { animation: keyframe_144 1s both; } @keyframes keyframe_144 { from { opacity: 1; } }" `); }); it('should pass the keyframes name through props along as well', () => { seedNextClassnames(['keyframe_880', 'keyframe_144']); const fadeIn = keyframes` from { opacity: 0; } `; const fadeOut = keyframes` from { opacity: 1; } `; const A = styled.div<{ animation: any }>` animation: ${props => props.animation} 1s both; `; const B = styled.div<{ animation: any }>` animation: ${props => props.animation} 1s both; `; /* Purposely rendering out of order to make sure the output looks right */ TestRenderer.create(<B animation={fadeOut} />); TestRenderer.create(<A animation={fadeIn} />); expect(getRenderedCSS()).toMatchInlineSnapshot(` "@-webkit-keyframes keyframe_880 { from { opacity: 0; } } @keyframes keyframe_880 { from { opacity: 0; } } .d { animation: keyframe_880 1s both; } .c { animation: keyframe_144 1s both; } @keyframes keyframe_144 { from { opacity: 1; } }" `); }); }); });
3,067
0
petrpan-code/styled-components/styled-components/packages/styled-components/src
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/ssr.test.tsx
/** * @jest-environment node */ import { resetStyled } from './utils'; import React from 'react'; import { renderToNodeStream, renderToString } from 'react-dom/server'; import stylisRTLPlugin from 'stylis-plugin-rtl'; import createGlobalStyle from '../constructors/createGlobalStyle'; import ServerStyleSheet from '../models/ServerStyleSheet'; import { StyleSheetManager } from '../models/StyleSheetManager'; jest.mock('../utils/nonce'); let styled: ReturnType<typeof resetStyled>; describe('ssr', () => { beforeEach(() => { jest.spyOn(console, 'warn').mockImplementation(() => {}); require('../utils/nonce').mockReset(); styled = resetStyled(true); }); it('should extract the CSS in a simple case', () => { const Heading = styled.h1` color: red; `; const sheet = new ServerStyleSheet(); const html = renderToString(sheet.collectStyles(<Heading>Hello SSR!</Heading>)); const css = sheet.getStyleTags(); expect(html).toMatchSnapshot(); expect(css).toMatchSnapshot(); }); it('should extract both global and local CSS', () => { const Component = createGlobalStyle` body { background: papayawhip; } `; const Heading = styled.h1` color: red; `; const sheet = new ServerStyleSheet(); const html = renderToString( sheet.collectStyles( <React.Fragment> <Component /> <Heading>Hello SSR!</Heading> </React.Fragment> ) ); const css = sheet.getStyleTags(); expect(html).toMatchSnapshot(); expect(css).toMatchSnapshot(); }); it('should not spill ServerStyleSheets into each other', () => { const A = styled.h1` color: red; `; const B = styled.h1` color: green; `; const sheetA = new ServerStyleSheet(); renderToString(sheetA.collectStyles(<A />)); const cssA = sheetA.getStyleTags(); const sheetB = new ServerStyleSheet(); renderToString(sheetB.collectStyles(<B />)); const cssB = sheetB.getStyleTags(); expect(cssA).toContain('red'); expect(cssA).not.toContain('green'); expect(cssB).not.toContain('red'); expect(cssB).toContain('green'); }); it('should add a nonce to the stylesheet if webpack nonce is detected in the global scope', () => { require('../utils/nonce').mockImplementation(() => 'foo'); const Component = createGlobalStyle` body { background: papayawhip; } `; const Heading = styled.h1` color: red; `; const sheet = new ServerStyleSheet(); const html = renderToString( sheet.collectStyles( <React.Fragment> <Component /> <Heading>Hello SSR!</Heading> </React.Fragment> ) ); const css = sheet.getStyleTags(); expect(html).toMatchSnapshot(); expect(css).toMatchSnapshot(); }); it('should render CSS in the order the components were defined, not rendered', () => { const ONE = styled.h1.withConfig({ componentId: 'ONE' })` color: red; `; const TWO = styled.h2.withConfig({ componentId: 'TWO' })` color: blue; `; const sheet = new ServerStyleSheet(); const html = renderToString( sheet.collectStyles( <div> <TWO /> <ONE /> </div> ) ); const css = sheet.getStyleTags(); expect(html).toMatchSnapshot(); expect(css).toMatchSnapshot(); }); it('should return a generated React style element', () => { const Component = createGlobalStyle` body { background: papayawhip; } `; const Heading = styled.h1` color: red; `; const sheet = new ServerStyleSheet(); renderToString( sheet.collectStyles( <React.Fragment> <Component /> <Heading>Hello SSR!</Heading> </React.Fragment> ) ); const [element] = sheet.getStyleElement(); expect(element.props.dangerouslySetInnerHTML).toBeDefined(); expect(element.props.children).not.toBeDefined(); expect(element.props).toMatchSnapshot(); }); it('should return a generated React style element with nonce if webpack nonce is preset in the global scope', () => { require('../utils/nonce').mockImplementation(() => 'foo'); const Component = createGlobalStyle` body { background: papayawhip; } `; const Heading = styled.h1` color: red; `; const sheet = new ServerStyleSheet(); renderToString( sheet.collectStyles( <React.Fragment> <Heading>Hello SSR!</Heading> <Component /> </React.Fragment> ) ); const [element] = sheet.getStyleElement(); expect(element.props.nonce).toBe('foo'); }); it('should interleave styles with rendered HTML when utilitizing streaming', () => { const Component = createGlobalStyle` body { background: papayawhip; } `; const Heading = styled.h1` color: red; `; const sheet = new ServerStyleSheet(); const jsx = sheet.collectStyles( <React.Fragment> <Component /> <Heading>Hello SSR!</Heading> </React.Fragment> ); // @ts-expect-error TODO ReadableStream vs Readable const stream = sheet.interleaveWithNodeStream(renderToNodeStream(jsx)); return new Promise<void>((resolve, reject) => { let received = ''; stream.on('data', chunk => { received += chunk; }); stream.on('end', () => { expect(received).toMatchSnapshot(); expect(sheet.sealed).toBe(true); resolve(); }); stream.on('error', reject); }); }); it('should interleave styles with rendered HTML when chunked streaming', () => { const Component = createGlobalStyle` body { background: papayawhip; } `; const Heading = styled.h1` color: red; `; const Body = styled.div` color: blue; `; const SideBar = styled.div` color: yellow; `; const Footer = styled.div` color: green; `; // This is the result of the above const expectedElements = '<div>*************************</div>'.repeat(100); const sheet = new ServerStyleSheet(); const jsx = sheet.collectStyles( <React.Fragment> <Component /> <Heading>Hello SSR!</Heading> <Body> {new Array(1000).fill(0).map((_, i) => ( <div key={i}>*************************</div> ))} </Body> <SideBar>SideBar</SideBar> <Footer>Footer</Footer> </React.Fragment> ); // @ts-expect-error TODO ReadableStream vs Readable const stream = sheet.interleaveWithNodeStream(renderToNodeStream(jsx)); const stream$ = new Promise<string>((resolve, reject) => { let received = ''; stream.on('data', chunk => { received += chunk; }); stream.on('end', () => resolve(received)); stream.on('error', reject); }); return stream$.then(received => { expect(sheet.sealed).toBe(true); expect(received.includes(expectedElements)).toBeTruthy(); expect(received).toMatch(/yellow/); expect(received).toMatch(/green/); }); }); it('should handle errors while streaming', () => { function ExplodingComponent(): JSX.Element { throw new Error('ahhh'); } const sheet = new ServerStyleSheet(); const jsx = sheet.collectStyles(<ExplodingComponent />); // @ts-expect-error TODO ReadableStream vs Readable const stream = sheet.interleaveWithNodeStream(renderToNodeStream(jsx)); return new Promise<void>(resolve => { stream.on('data', () => {}); stream.on('error', err => { expect(err).toMatchSnapshot(); expect(sheet.sealed).toBe(true); resolve(); }); }); }); it('should not interleave style tags into textarea elements', () => { const StyledTextArea = styled.textarea<{ height: number }>` height: ${props => `${props.height}px`}; `; const sheet = new ServerStyleSheet(); // Currently we cannot set the chunk size to read with react renderToNodeStream, so to ensure // that multiple chunks are created, we initialize a large array of styled text areas. We give // each textarea a different style to ensure a large enough number of style tags are generated // to be interleaved in the document const jsx = sheet.collectStyles( <React.Fragment> {new Array(500).fill(0).map((_, i) => ( <StyledTextArea key={i} className="test-textarea" onChange={() => {}} value={`Textarea ${i}`} height={i} /> ))} </React.Fragment> ); // @ts-expect-error TODO ReadableStream vs Readable const stream = sheet.interleaveWithNodeStream(renderToNodeStream(jsx)); return new Promise<void>((resolve, reject) => { let received = ''; stream.on('data', chunk => { received += chunk; }); stream.on('end', () => { const styleTagsInsideTextarea = received.match(/<\/style>[^<]*<\/textarea>/g); expect(styleTagsInsideTextarea).toBeNull(); resolve(); }); stream.on('error', reject); }); }); it('should throw if interleaveWithNodeStream is called twice', () => { const Component = createGlobalStyle` body { background: papayawhip; } `; const Heading = styled.h1` color: red; `; const sheet = new ServerStyleSheet(); const jsx = sheet.collectStyles( <React.Fragment> <Component /> <Heading>Hello SSR!</Heading> </React.Fragment> ); expect(() => // @ts-expect-error TODO ReadableStream vs Readable sheet.interleaveWithNodeStream(sheet.interleaveWithNodeStream(renderToNodeStream(jsx))) ).toThrowErrorMatchingSnapshot(); }); it('should throw if getStyleTags is called after interleaveWithNodeStream is called', () => { const Component = createGlobalStyle` body { background: papayawhip; } `; const Heading = styled.h1` color: red; `; const sheet = new ServerStyleSheet(); const jsx = sheet.collectStyles( <React.Fragment> <Component /> <Heading>Hello SSR!</Heading> </React.Fragment> ); // @ts-expect-error TODO ReadableStream vs Readable sheet.interleaveWithNodeStream(renderToNodeStream(jsx)); expect(sheet.getStyleTags).toThrowErrorMatchingSnapshot(); }); it('should throw if getStyleElement is called after interleaveWithNodeStream is called', () => { const Component = createGlobalStyle` body { background: papayawhip; } `; const Heading = styled.h1` color: red; `; const sheet = new ServerStyleSheet(); const jsx = sheet.collectStyles( <React.Fragment> <Component /> <Heading>Hello SSR!</Heading> </React.Fragment> ); // @ts-expect-error TODO ReadableStream vs Readable sheet.interleaveWithNodeStream(renderToNodeStream(jsx)); expect(sheet.getStyleElement).toThrowErrorMatchingSnapshot(); }); it('should throw if getStyleTags is called after streaming is complete', () => { const Component = createGlobalStyle` body { background: papayawhip; } `; const Heading = styled.h1` color: red; `; const sheet = new ServerStyleSheet(); const jsx = sheet.collectStyles( <React.Fragment> <Component /> <Heading>Hello SSR!</Heading> </React.Fragment> ); // @ts-expect-error TODO ReadableStream vs Readable const stream = sheet.interleaveWithNodeStream(renderToNodeStream(jsx)); return new Promise<void>((resolve, reject) => { let received = ''; stream.on('data', chunk => { received += chunk; }); stream.on('end', () => { expect(received).toMatchSnapshot(); expect(sheet.sealed).toBe(true); expect(sheet.getStyleTags).toThrowErrorMatchingSnapshot(); resolve(); }); stream.on('error', reject); }); }); it('should throw if getStyleElement is called after streaming is complete', () => { const Component = createGlobalStyle` body { background: papayawhip; } `; const Heading = styled.h1` color: red; `; const sheet = new ServerStyleSheet(); const jsx = sheet.collectStyles( <React.Fragment> <Component /> <Heading>Hello SSR!</Heading> </React.Fragment> ); // @ts-expect-error TODO ReadableStream vs Readable const stream = sheet.interleaveWithNodeStream(renderToNodeStream(jsx)); return new Promise<void>((resolve, reject) => { let received = ''; stream.on('data', chunk => { received += chunk; }); stream.on('end', () => { expect(received).toMatchSnapshot(); expect(sheet.sealed).toBe(true); expect(sheet.getStyleElement).toThrowErrorMatchingSnapshot(); resolve(); }); stream.on('error', reject); }); }); it('should work with stylesheet manager and passed stylis plugins', () => { const Heading = styled.h1` padding-left: 5px; `; const sheet = new ServerStyleSheet(); const html = renderToString( sheet.collectStyles( <StyleSheetManager stylisPlugins={[stylisRTLPlugin]}> <Heading>Hello SSR!</Heading> </StyleSheetManager> ) ); const css = sheet.getStyleTags(); expect(html).toMatchInlineSnapshot(` <h1 class="sc-a b"> Hello SSR! </h1> `); expect(css).toMatchInlineSnapshot(` <style data-styled="true" data-styled-version="JEST_MOCK_VERSION" > .b{padding-right:5px;}/*!sc*/ data-styled.g1[id="sc-a"]{content:"b,"}/*!sc*/ </style> `); }); });
3,068
0
petrpan-code/styled-components/styled-components/packages/styled-components/src
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/staticCaching.test.ts
import { resetStyled } from './utils'; let styled: ReturnType<typeof resetStyled>; describe('static style caching', () => { beforeEach(() => { styled = resetStyled(); }); describe('non-production modes', () => { it('should mark styles without any functions as not static', () => { const TOP_AS_NUMBER = 10; const FONT_SIZE_NUMBER = 14; const Comp = styled.div` color: purple; font-size: ${FONT_SIZE_NUMBER}px position: absolute; top: ${TOP_AS_NUMBER} `; expect(Comp.componentStyle.isStatic).toEqual(false); }); it('should mark styles with a nested styled component as not static', () => { const NestedComp = styled.div``; const Comp = styled.div` ${NestedComp} { color: purple; } `; expect(Comp.componentStyle.isStatic).toEqual(false); }); it('should mark styles with a dynamic style as not not static', () => { const Comp = styled.div` color: ${props => props.color}; `; expect(Comp.componentStyle.isStatic).toEqual(false); }); it('should mark a static style wrapping a dynamic style as not static', () => { const Inner = styled.div` color: ${props => props.color}; `; const Outer = styled(Inner)` padding: 5px; `; expect(Outer.componentStyle.isStatic).toEqual(false); }); }); describe('production mode', () => { beforeEach(() => { process.env.NODE_ENV = 'production'; }); it('should mark styles without any functions as static', () => { const TOP_AS_NUMBER = 10; const FONT_SIZE_NUMBER = 14; const Comp = styled.div` color: purple; font-size: ${FONT_SIZE_NUMBER}px position: absolute; top: ${TOP_AS_NUMBER} `; expect(Comp.componentStyle.isStatic).toEqual(true); }); it('should mark styles with a nested styled component as static', () => { const NestedComp = styled.div``; const Comp = styled.div` ${NestedComp} { color: purple; } `; expect(Comp.componentStyle.isStatic).toEqual(true); }); it('should mark styles with a dynamic style as not static', () => { const Comp = styled.div` color: ${props => props.color}; `; expect(Comp.componentStyle.isStatic).toEqual(false); }); it('should mark a static style wrapping a dynamic style as not static', () => { const Inner = styled.div` color: ${props => props.color}; `; const Outer = styled(Inner)` padding: 5px; `; expect(Outer.componentStyle.isStatic).toEqual(false); }); }); });
3,069
0
petrpan-code/styled-components/styled-components/packages/styled-components/src
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/styles.test.tsx
import React from 'react'; import TestRenderer from 'react-test-renderer'; import { ThemeProvider } from '../base'; import css from '../constructors/css'; import { mainSheet } from '../models/StyleSheetManager'; import * as nonce from '../utils/nonce'; import { getRenderedCSS, resetStyled } from './utils'; jest.mock('../utils/nonce'); jest.spyOn(nonce, 'default').mockImplementation(() => 'foo'); let styled: ReturnType<typeof resetStyled>; describe('with styles', () => { /** * Make sure the setup is the same for every test */ beforeEach(() => { document.head.innerHTML = ''; styled = resetStyled(); }); it('should append a style', () => { const rule = 'color: blue;'; const Comp = styled.div` ${rule}; `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { color: blue; }" `); }); it('should append multiple styles', () => { const rule1 = 'color: blue;'; const rule2 = 'background: red;'; const Comp = styled.div` ${rule1} ${rule2}; `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { color: blue; background: red; }" `); }); it('amperstand should refer to the static class when making a self-referential combo selector', () => { const Comp = styled.div<{ color: string }>` background: red; color: ${p => p.color}; &&& { border: 1px solid red; } &[disabled] { color: red; & + & { margin-bottom: 4px; } & > & { margin-top: 4px; } } & + & { margin-left: 4px; } & + & ~ & { background: black; } & ~ & { margin-right: 4px; } & > & { margin-top: 4px; } .foo & { color: silver; } .foo > & { color: green; } &:not(& ~ &) { color: cornflowerblue; } `; TestRenderer.create( <React.Fragment> <Comp color="white" /> <Comp color="red" /> </React.Fragment> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { background: red; color: white; } .a.a.a { border: 1px solid red; } .a[disabled] { color: red; } .a[disabled] + .a[disabled] { margin-bottom: 4px; } .a[disabled] > .a[disabled] { margin-top: 4px; } .sc-gRlPMw + .sc-gRlPMw { margin-left: 4px; } .sc-gRlPMw + .sc-gRlPMw ~ .sc-gRlPMw { background: black; } .sc-gRlPMw ~ .sc-gRlPMw { margin-right: 4px; } .sc-gRlPMw > .sc-gRlPMw { margin-top: 4px; } .foo .a { color: silver; } .foo > .a { color: green; } .a:not(.a ~ .a) { color: cornflowerblue; } .b { background: red; color: red; } .b.b.b { border: 1px solid red; } .b[disabled] { color: red; } .b[disabled] + .b[disabled] { margin-bottom: 4px; } .b[disabled] > .b[disabled] { margin-top: 4px; } .sc-gRlPMw + .sc-gRlPMw { margin-left: 4px; } .sc-gRlPMw + .sc-gRlPMw ~ .sc-gRlPMw { background: black; } .sc-gRlPMw ~ .sc-gRlPMw { margin-right: 4px; } .sc-gRlPMw > .sc-gRlPMw { margin-top: 4px; } .foo .b { color: silver; } .foo > .b { color: green; } .b:not(.b ~ .b) { color: cornflowerblue; }" `); }); it('should handle inline style objects', () => { const rule1 = { backgroundColor: 'blue', }; const Comp = styled.div` ${rule1}; `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { background-color: blue; }" `); }); it('should handle inline style objects with media queries', () => { const rule1 = { backgroundColor: 'blue', '@media screen and (min-width: 250px)': { backgroundColor: 'red', }, }; const Comp = styled.div` ${rule1}; `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { background-color: blue; } @media screen and (min-width:250px) { .a { background-color: red; } }" `); }); it('should handle inline style objects with pseudo selectors', () => { const rule1 = { backgroundColor: 'blue', '&:hover': { color: 'green', }, }; const Comp = styled.div` ${rule1}; `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { background-color: blue; } .a:hover { color: green; }" `); }); it('should handle inline style objects with nesting', () => { const rule1 = { backgroundColor: 'blue', '> h1': { color: 'white', }, }; const Comp = styled.div` ${rule1}; `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { background-color: blue; } .a > h1 { color: white; }" `); }); it('should handle inline style objects with contextual selectors', () => { const rule1 = { backgroundColor: 'blue', 'html.something &': { color: 'white', }, }; const Comp = styled.div` ${rule1}; `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { background-color: blue; } html.something .a { color: white; }" `); }); it('should inject styles of multiple components', () => { const firstRule = 'background: blue;'; const secondRule = 'background: red;'; const FirstComp = styled.div` ${firstRule}; `; const SecondComp = styled.div` ${secondRule}; `; TestRenderer.create(<FirstComp />); TestRenderer.create(<SecondComp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { background: blue; } .b { background: red; }" `); }); it('should inject styles of multiple components based on creation, not rendering order', () => { const firstRule = 'content: "first rule";'; const secondRule = 'content: "second rule";'; const FirstComp = styled.div` ${firstRule}; `; const SecondComp = styled.div` ${secondRule}; `; // Switch rendering order, shouldn't change injection order TestRenderer.create(<SecondComp />); TestRenderer.create(<FirstComp />); // Classes _do_ get generated in the order of rendering but that's ok expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { content: "first rule"; } .a { content: "second rule"; }" `); }); it('should strip a JS-style (invalid) comment in the styles', () => { const comment = '// This is an invalid comment'; const rule = 'color: blue;'; // prettier-ignore const Comp = styled.div` ${comment} ${rule} `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { color: blue; }" `); }); it('should respect removed rules', () => { const Heading = styled.h1` color: red; `; const Text = styled.span` color: green; `; TestRenderer.create( <Heading> <Text /> </Heading> ); mainSheet.clearRules(Text.styledComponentId); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { color: red; }" `); }); it('should add a webpack nonce to the style tags if one is available in the global scope', () => { const rule = 'color: blue;'; const Comp = styled.div` ${rule}; `; TestRenderer.create(<Comp />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { color: blue; }" `); Array.from(document.querySelectorAll('style')).forEach(el => { expect(el.getAttribute('nonce')).toBe('foo'); }); }); it('should handle functions inside TTL that return css constructor', () => { const Comp = styled.div<{ variant: 'foo' | 'bar' }>` color: ${p => (p.variant === 'bar' ? css`green` : 'red')}; `; TestRenderer.create(<Comp variant="bar" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { color: green; }" `); }); it('failing test', () => { interface IconProps { color?: string; rounded?: boolean; spin?: boolean; } const spinCss = css` @keyframes iconSpin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } animation-name: iconSpin; animation-duration: 1000ms; animation-iteration-count: infinite; animation-timing-function: linear; `; const Wrapper = styled.span<IconProps>` vertical-align: middle; display: inline-block; line-height: ${({ theme }) => theme.lineHeights.sm}; font-size: ${({ theme }) => theme.fontSizes.sm}; & > svg { stroke: ${({ theme, color }): string => color && color !== 'inherit' ? theme.colors[color] : 'currentColor'}; ${({ spin }): any => (spin ? spinCss : '')}; } ${({ rounded }): string => (rounded ? 'border-radius: 9999px;' : '')}; `; TestRenderer.create( // spinCss should only be added if spin is true. Meanwhile, when any icon component in the application receives spin=true prop, all icons in the app start spinning (see video). <ThemeProvider theme={{ colors: { red: 'darkred' }, fontSizes: { sm: '14px' }, lineHeights: { sm: '20px' }, }} > <Wrapper /> <Wrapper spin /> <Wrapper color="red" /> </ThemeProvider> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".a { vertical-align: middle; display: inline-block; line-height: 20px; font-size: 14px; } .a > svg { stroke: currentColor; } .b { vertical-align: middle; display: inline-block; line-height: 20px; font-size: 14px; } .b > svg { stroke: currentColor; animation-name: iconSpin; animation-duration: 1000ms; animation-iteration-count: infinite; animation-timing-function: linear; } @keyframes iconSpin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .c { vertical-align: middle; display: inline-block; line-height: 20px; font-size: 14px; } .c > svg { stroke: darkred; }" `); }); });
3,070
0
petrpan-code/styled-components/styled-components/packages/styled-components/src
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/theme.test.tsx
import React, { Component } from 'react'; import { renderIntoDocument } from 'react-dom/test-utils'; import TestRenderer from 'react-test-renderer'; import withTheme from '../hoc/withTheme'; import ThemeProvider, { DefaultTheme } from '../models/ThemeProvider'; import { getRenderedCSS, resetStyled } from './utils'; let styled: ReturnType<typeof resetStyled>; describe('theming', () => { beforeEach(() => { jest.spyOn(console, 'error').mockImplementation(() => {}); styled = resetStyled(); }); it('should inject props.theme into a styled component', () => { const Comp = styled.div` color: ${props => props.theme.color}; `; const theme = { color: 'black' }; TestRenderer.create( <ThemeProvider theme={theme}> <Comp /> </ThemeProvider> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: black; }" `); }); it('should inject props.theme into a styled component multiple levels deep', () => { const Comp = styled.div` color: ${props => props.theme.color}; `; const theme = { color: 'black' }; TestRenderer.create( <ThemeProvider theme={theme}> <div> <div> <Comp /> </div> </div> </ThemeProvider> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: black; }" `); }); it('should properly allow a component to fallback to its default props when a theme is not provided', () => { const Comp1 = styled.div` color: ${props => props.theme.test.color}; `; Comp1.defaultProps = { theme: { test: { color: 'purple', }, }, }; TestRenderer.create( <div> <Comp1 /> </div> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: purple; }" `); }); // https://github.com/styled-components/styled-components/issues/344 it('should use ThemeProvider theme instead of defaultProps theme', () => { const Comp1 = styled.div` color: ${props => props.theme.test.color}; `; Comp1.defaultProps = { theme: { test: { color: 'purple', }, }, }; const theme = { test: { color: 'green' } }; TestRenderer.create( <ThemeProvider theme={theme}> <Comp1 /> </ThemeProvider> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: green; }" `); }); it('should properly allow a component to override the theme with a prop even if it is equal to defaultProps theme', () => { const Comp1 = styled.div` color: ${props => props.theme.test.color}; `; Comp1.defaultProps = { theme: { test: { color: 'purple', }, }, }; const theme = { test: { color: 'green' } }; TestRenderer.create( <ThemeProvider theme={theme}> <Comp1 theme={{ test: { color: 'purple' } }} /> </ThemeProvider> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: purple; }" `); }); it('should properly allow a component to override the theme with a prop', () => { const Comp = styled.div` color: ${props => props.theme.color}; `; const theme = { color: 'purple', }; TestRenderer.create( <div> <ThemeProvider theme={theme}> <Comp theme={{ color: 'red' }} /> </ThemeProvider> </div> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: red; }" `); }); it('should only inject props.theme into styled components within its child component tree', () => { const Comp1 = styled.div` color: ${props => props.theme.color || 'red'}; `; const Comp2 = styled.div` color: ${props => props.theme.color || 'red'}; `; const theme = { color: 'black' }; TestRenderer.create( <div> <ThemeProvider theme={theme}> <div> <Comp1 /> </div> </ThemeProvider> <Comp2 /> </div> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".c { color: black; } .d { color: red; }" `); }); it('should inject props.theme into all styled components within the child component tree', () => { const Comp1 = styled.div` color: ${props => props.theme.color}; `; const Comp2 = styled.div` background: ${props => props.theme.color}; `; const theme = { color: 'black' }; TestRenderer.create( <ThemeProvider theme={theme}> <div> <div> <Comp1 /> </div> <Comp2 /> </div> </ThemeProvider> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".c { color: black; } .d { background: black; }" `); }); it('should inject new CSS when the theme changes', () => { const Comp = styled.div` color: ${props => props.theme.color}; `; const originalTheme = { color: 'black' }; const newTheme = { color: 'blue' }; let theme = originalTheme; // Force render the component const renderComp = () => { TestRenderer.create( <ThemeProvider theme={theme}> <Comp /> </ThemeProvider> ); }; renderComp(); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: black; }" `); // Change the theme theme = newTheme; renderComp(); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: black; } .c { color: blue; }" `); }); it('should properly render with the same theme from default props on re-render', () => { const Comp1 = styled.div` color: ${props => props.theme.color}; `; Comp1.defaultProps = { theme: { color: 'purple', }, }; const jsx = <Comp1 />; const wrapper = TestRenderer.create(jsx); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: purple; }" `); wrapper.update(jsx); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: purple; }" `); }); it('should properly update style if theme is changed', () => { const Comp1 = styled.div` color: ${props => props.theme.color}; `; const wrapper = TestRenderer.create( <ThemeProvider theme={{ color: 'purple', }} > <Comp1 /> </ThemeProvider> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: purple; }" `); wrapper.update( <ThemeProvider theme={{ color: 'pink', }} > <Comp1 /> </ThemeProvider> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: purple; } .c { color: pink; }" `); }); it('should properly update style if props used in styles is changed', () => { const Comp1 = styled.div<{ zIndex?: number }>` color: ${props => props.theme.color}; z-index: ${props => props.zIndex}; `; Comp1.defaultProps = { zIndex: 0, }; const wrapper = TestRenderer.create( <ThemeProvider theme={{ color: 'purple', }} > <Comp1 /> </ThemeProvider> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: purple; z-index: 0; }" `); wrapper.update( <ThemeProvider theme={{ color: 'pink', }} > <Comp1 /> </ThemeProvider> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: purple; z-index: 0; } .c { color: pink; z-index: 0; }" `); Comp1.defaultProps.zIndex = 1; wrapper.update( <ThemeProvider theme={{ color: 'pink', }} > <Comp1 /> </ThemeProvider> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: purple; z-index: 0; } .c { color: pink; z-index: 0; } .d { color: pink; z-index: 1; }" `); }); it('should change the classnames when the theme changes', () => { const Comp = styled.div` color: ${props => props.theme.color}; `; const originalTheme = { color: 'black' }; const newTheme = { color: 'blue' }; const Theme = ({ theme }: any) => ( <ThemeProvider theme={theme}> <Comp /> </ThemeProvider> ); const wrapper = TestRenderer.create(<Theme theme={originalTheme} />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: black; }" `); expect(wrapper.root.findByType('div').props.className).toBe('sc-a b'); // Change theme wrapper.update(Theme({ theme: newTheme })); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: black; } .c { color: blue; }" `); expect(wrapper.root.findByType('div').props.className).toBe('sc-a c'); }); it('should inject props.theme into a component that uses withTheme hoc', () => { const originalTheme = { color: 'black' }; const MyDiv = ({ theme }: any) => <div>{theme.color}</div>; const MyDivWithTheme = withTheme(MyDiv); const wrapper = TestRenderer.create( <ThemeProvider theme={originalTheme}> <MyDivWithTheme /> </ThemeProvider> ); expect(wrapper.root.findByType('div').props.children).toBe('black'); }); it('should properly update theme prop on hoc component when theme is changed', () => { const MyDiv = ({ theme }: any) => <div>{theme.color}</div>; const MyDivWithTheme = withTheme(MyDiv); const originalTheme = { color: 'black' }; const newTheme = { color: 'blue' }; const Theme = ({ theme }: any) => ( <ThemeProvider theme={theme}> <MyDivWithTheme /> </ThemeProvider> ); const wrapper = TestRenderer.create(<Theme key="a" theme={originalTheme} />); expect(wrapper.root.findByType('div').props.children).toBe('black'); // Change theme wrapper.update(<Theme key="a" theme={newTheme} />); expect(wrapper.root.findByType('div').props.children).toBe('blue'); }); // https://github.com/styled-components/styled-components/issues/445 it('should use ThemeProvider theme instead of defaultProps theme after initial render', () => { const Text = styled.div` color: ${props => props.theme.color}; `; Text.defaultProps = { theme: { color: 'purple', }, }; const Theme = (props: React.ComponentProps<typeof Text>) => ( <ThemeProvider theme={{ color: 'green' }}> <Text {...props} /> </ThemeProvider> ); const wrapper = TestRenderer.create(<Theme key="a" data-prop="foo" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: green; }" `); wrapper.update(<Theme key="a" data-prop="bar" />); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { color: green; }" `); }); // https://github.com/styled-components/styled-components/issues/596 it('should hoist static properties when using withTheme', () => { class MyComponent extends Component<any, any> { static myStaticProperty = true; } const MyComponentWithTheme = withTheme(MyComponent); expect(MyComponentWithTheme.myStaticProperty).toBe(true); }); it('should only pass the theme prop', () => { class Comp extends Component<any, any> { render() { return <div />; } } const CompWithTheme = withTheme(Comp); const wrapper = TestRenderer.create( <ThemeProvider theme={{}}> <CompWithTheme /> </ThemeProvider> ); const inner = wrapper.root.findByType(Comp); expect(Object.keys(inner.props).length).toEqual(1); expect(inner.props).toEqual({ theme: {} }); }); it('should forward refs', () => { class Comp extends Component<any, any> { render() { return <div {...this.props} />; } } const CompWithTheme = withTheme(Comp); const ref = React.createRef<typeof Comp>(); renderIntoDocument( <ThemeProvider theme={{}}> <CompWithTheme ref={ref} /> </ThemeProvider> ); expect(ref.current).toBeInstanceOf(Comp); }); // https://github.com/styled-components/styled-components/issues/1130 it('should not break without a ThemeProvider if it has a defaultTheme', () => { const MyDiv: React.FunctionComponent<{ theme: DefaultTheme }> = ({ theme }) => ( <div>{theme.color}</div> ); const MyDivWithTheme = withTheme(MyDiv); const theme = { color: 'red' }; const newTheme = { color: 'blue' }; const consoleWarn = console.warn; jest .spyOn(console, 'warn') .mockImplementation(msg => !msg.includes('You are not using a ThemeProvider') ? consoleWarn(msg) : null ); MyDivWithTheme.defaultProps = { theme }; const wrapper = TestRenderer.create(<MyDivWithTheme />); expect(wrapper.root.findByType('div').props.children).toBe('red'); // Change theme MyDivWithTheme.defaultProps = { theme: newTheme }; // Change theme wrapper.update(<MyDivWithTheme />); expect(wrapper.root.findByType('div').props.children).toBe('blue'); }); // https://github.com/styled-components/styled-components/issues/1776 it('should allow module objects to be passed as themes', () => { const theme = { borderRadius: '2px', palette: { black: '#000', white: '#fff', // Flow has limited support for Symbols and computed properties; // see <https://github.com/facebook/flow/issues/3258>. [Symbol.toStringTag]: 'Module', }, // Flow has limited support for Symbols and computed properties; // see <https://github.com/facebook/flow/issues/3258>. [Symbol.toStringTag]: 'Module', }; const Comp1 = styled.div` background-color: ${({ theme }) => theme.palette.white}; color: ${({ theme }) => theme.palette.black}; `; expect(() => { TestRenderer.create( <ThemeProvider theme={theme}> <Comp1 /> </ThemeProvider> ); }).not.toThrow('plain object'); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { background-color: #fff; color: #000; }" `); }); it('should allow other complex objects to be passed as themes', () => { class Theme { borderRadius: string; constructor(borderRadius: string) { this.borderRadius = borderRadius; } } const theme = new Theme('2px'); const Comp1 = styled.div` border-radius: ${({ theme }) => theme.borderRadius}; `; TestRenderer.create( <ThemeProvider theme={theme}> <Comp1 /> </ThemeProvider> ); expect(getRenderedCSS()).toMatchInlineSnapshot(` ".b { border-radius: 2px; }" `); }); it('should not allow the theme to be null', () => { expect(() => { // HACK: work around the problem without changing the snapshots // these tests need to be changed to use error boundaries instead const mock = jest.spyOn(console, 'error').mockImplementation(() => {}); TestRenderer.create( // @ts-expect-error properly catching null theme <ThemeProvider theme={null}> <div /> </ThemeProvider> ); expect(mock).toHaveBeenCalledTimes(1); }).toThrowErrorMatchingSnapshot(); }); it('should not allow the theme to be an array', () => { expect(() => { // HACK: work around the problem without changing the snapshots // these tests need to be changed to use error boundaries instead const mock = jest.spyOn(console, 'error').mockImplementation(() => {}); TestRenderer.create( <ThemeProvider theme={['a', 'b', 'c']}> <div /> </ThemeProvider> ); expect(mock).toHaveBeenCalledTimes(1); }).toThrowErrorMatchingSnapshot(); }); it('should not allow the theme to be a non-object', () => { expect(() => { // HACK: work around the problem without changing the snapshots // these tests need to be changed to use error boundaries instead const mock = jest.spyOn(console, 'error').mockImplementation(() => {}); TestRenderer.create( // @ts-expect-error invalid input <ThemeProvider theme={42}> <div /> </ThemeProvider> ); expect(mock).toHaveBeenCalledTimes(1); }).toThrowErrorMatchingSnapshot(); }); });
3,074
0
petrpan-code/styled-components/styled-components/packages/styled-components/src
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/warnOnDynamicCreation.test.tsx
import React from 'react'; import TestRenderer from 'react-test-renderer'; import { resetStyled } from './utils'; describe('warns on dynamic creation', () => { let warn: ReturnType<typeof jest.spyOn>; let styled: ReturnType<typeof resetStyled>; beforeEach(() => { warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); styled = resetStyled(); }); afterEach(() => { warn.mockReset(); }); it('should warn when a component was created dynamically', () => { const Outer = () => { const Inner = styled.div` color: palevioletred; `; return <Inner />; }; TestRenderer.create(<Outer />); expect(warn).toHaveBeenCalledTimes(1); expect(warn.mock.calls[0][0]).toMatch(/has been created dynamically/i); }); it('should warn only once for a given ID', () => { const Outer = () => { const Inner = styled.div.withConfig({ displayName: 'Inner', componentId: 'Inner', })` color: palevioletred; `; return <Inner />; }; TestRenderer.create(<Outer />); TestRenderer.create(<Outer />); expect(warn).toHaveBeenCalledTimes(1); }); it('should not warn in any other case', () => { const Inner = styled.div` color: palevioletred; `; const Outer = () => <Inner />; TestRenderer.create(<Outer />); expect(warn).toHaveBeenCalledTimes(0); }); });
3,075
0
petrpan-code/styled-components/styled-components/packages/styled-components/src
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/warnTooManyClasses.test.tsx
import React from 'react'; import TestRenderer from 'react-test-renderer'; import { LIMIT } from '../utils/createWarnTooManyClasses'; import { resetStyled } from './utils'; let styled: ReturnType<typeof resetStyled>; describe('warn too many classes', () => { /** * Make sure the setup is the same for every test */ beforeEach(() => { jest.spyOn(console, 'warn').mockImplementation(() => {}); styled = resetStyled(); }); it('should warn once', () => { const Comp = styled.div<{ size: number }>` width: ${props => props.size}; `; for (let i = 0; i < LIMIT + 1; i++) { TestRenderer.create(<Comp size={i} />); } expect(console.warn).toHaveBeenCalledTimes(1); }); it(`should warn if number of classes is ${LIMIT}`, () => { const Comp = styled.div<{ size: number }>` width: ${props => props.size}; `; for (let i = 0; i < LIMIT; i++) { TestRenderer.create(<Comp size={i} />); } expect(console.warn).toHaveBeenCalledTimes(1); }); it(`should not warn if number of classes is below ${LIMIT}`, () => { const Comp = styled.div<{ size: number }>` width: ${props => props.size}; `; for (let i = 0; i < LIMIT - 1; i++) { TestRenderer.create(<Comp size={i} />); } expect(console.warn).toHaveBeenCalledTimes(0); }); });
3,076
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/test
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/__snapshots__/attrs.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`attrs does not pass transient props to HTML element 1`] = ` <div className="sc-a sc-b c" /> `; exports[`attrs merge attrs 1`] = ` <button className="sc-a" tabIndex={0} type="submit" /> `; exports[`attrs merge attrs when inheriting SC 1`] = ` <button className="sc-a sc-b" tabIndex={0} type="submit" /> `; exports[`attrs pass a React component 1`] = ` <button> <p> React Component </p> </button> `; exports[`attrs pass a simple attr via function with object return 1`] = ` <button className="sc-a" type="button" /> `; exports[`attrs pass a simple attr via object 1`] = ` <button className="sc-a" type="button" /> `; exports[`attrs pass attrs to style block 1`] = ` <a className="sc-a b" data-active-class-name="--is-active" href="#" /> `; exports[`attrs pass props to the attr function 1`] = ` <button className="sc-a" type="button" /> `; exports[`attrs pass props to the attr function 2`] = ` <button className="sc-a" type="submit" /> `; exports[`attrs should apply given "as" prop to the progressive type 1`] = ` <video className="sc-a" loop={true} /> `; exports[`attrs should merge className 1`] = ` <div className="sc-a meow nya" /> `; exports[`attrs should merge className even if its a function 1`] = ` <div className="sc-a meow nya" /> `; exports[`attrs should merge className even if its a function 2`] = ` <div className="sc-a meow purr" /> `; exports[`attrs should override children of course 1`] = ` <div className="sc-a" > <span> Amazing </span> </div> `; exports[`attrs should pass through children as a normal prop 1`] = ` <div className="sc-a" > Probably a bad idea </div> `; exports[`attrs should pass through complex children as well 1`] = ` <div className="sc-a" > <span> Probably a bad idea </span> </div> `; exports[`attrs should replace props with attrs 1`] = ` <button className="sc-a" tabIndex={0} type="button" /> `; exports[`attrs should replace props with attrs 2`] = ` <button className="sc-a" tabIndex={0} type="button" /> `; exports[`attrs should replace props with attrs 3`] = ` <button className="sc-a" tabIndex={0} type="button" /> `; exports[`attrs should work with data and aria attributes 1`] = ` <div aria-label="A simple FooBar" className="sc-a" data-foo="bar" /> `; exports[`attrs work fine with a function that returns an empty object 1`] = ` <div className="sc-a" /> `; exports[`attrs work fine with an empty object 1`] = ` <div className="sc-a" /> `;
3,077
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/test
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/__snapshots__/expanded-api.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`expanded api "as" prop changes the rendered element type 1`] = ` <span className="sc-a b" /> `; exports[`expanded api "as" prop changes the rendered element type when used with attrs 1`] = ` <header className="sc-a b" /> `; exports[`expanded api "as" prop works with custom components 1`] = ` <figure className="sc-a b" /> `; exports[`expanded api chaining should keep the last value passed in when merging 1`] = ` <div className="dn-5-id-4" /> `; exports[`expanded api chaining should merge the options strings 1`] = ` <div className="dn-2-id-1" /> `; exports[`expanded api componentId should be attached if passed in 1`] = ` <div className="LOLOMG" /> `; exports[`expanded api componentId should be attached if passed in 2`] = ` <div className="OMGLOL" /> `; exports[`expanded api componentId should be combined with displayName if both passed in 1`] = ` <div className="Comp-LOLOMG" /> `; exports[`expanded api componentId should be combined with displayName if both passed in 2`] = ` <div className="Comp2-OMGLOL" /> `; exports[`expanded api componentId should be generated as "sc" + hash 1`] = ` <div className="sc-a" /> `; exports[`expanded api componentId should be generated as "sc" + hash 2`] = ` <div className="sc-b" /> `; exports[`expanded api componentId should be generated from displayName + hash 1`] = ` <div className="Comp-a" /> `; exports[`expanded api componentId should be generated from displayName + hash 2`] = ` <div className="Comp2-b" /> `;
3,078
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/test
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/__snapshots__/props.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`props shouldForwardProp should inherit shouldForwardProp for wrapped styled components 2`] = ` [ <div className="sc-a c" id="test-1" />, <div className="sc-a sc-b d" id="test-2" />, ] `;
3,079
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/test
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/__snapshots__/ssr.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`ssr should add a nonce to the stylesheet if webpack nonce is detected in the global scope 1`] = ` <h1 class="sc-b c"> Hello SSR! </h1> `; exports[`ssr should add a nonce to the stylesheet if webpack nonce is detected in the global scope 2`] = ` <style nonce="foo" data-styled="true" data-styled-version="JEST_MOCK_VERSION" > body{background:papayawhip;}/*!sc*/ data-styled.g1[id="sc-global-a1"]{content:"sc-global-a1,"}/*!sc*/ .c{color:red;}/*!sc*/ data-styled.g2[id="sc-b"]{content:"c,"}/*!sc*/ </style> `; exports[`ssr should extract both global and local CSS 1`] = ` <h1 class="sc-b c"> Hello SSR! </h1> `; exports[`ssr should extract both global and local CSS 2`] = ` <style data-styled="true" data-styled-version="JEST_MOCK_VERSION" > body{background:papayawhip;}/*!sc*/ data-styled.g1[id="sc-global-a1"]{content:"sc-global-a1,"}/*!sc*/ .c{color:red;}/*!sc*/ data-styled.g2[id="sc-b"]{content:"c,"}/*!sc*/ </style> `; exports[`ssr should extract the CSS in a simple case 1`] = ` <h1 class="sc-a b"> Hello SSR! </h1> `; exports[`ssr should extract the CSS in a simple case 2`] = ` <style data-styled="true" data-styled-version="JEST_MOCK_VERSION" > .b{color:red;}/*!sc*/ data-styled.g1[id="sc-a"]{content:"b,"}/*!sc*/ </style> `; exports[`ssr should handle errors while streaming 1`] = `[Error: ahhh]`; exports[`ssr should interleave styles with rendered HTML when utilitizing streaming 1`] = ` <style data-styled="true" data-styled-version="JEST_MOCK_VERSION" > body{background:papayawhip;}/*!sc*/ data-styled.g1[id="sc-global-a1"]{content:"sc-global-a1,"}/*!sc*/ .c{color:red;}/*!sc*/ data-styled.g2[id="sc-b"]{content:"c,"}/*!sc*/ </style> <h1 class="sc-b c"> Hello SSR! </h1> `; exports[`ssr should render CSS in the order the components were defined, not rendered 1`] = ` <div> <h2 class="TWO a"> </h2> <h1 class="ONE b"> </h1> </div> `; exports[`ssr should render CSS in the order the components were defined, not rendered 2`] = ` <style data-styled="true" data-styled-version="JEST_MOCK_VERSION" > .b{color:red;}/*!sc*/ data-styled.g1[id="ONE"]{content:"b,"}/*!sc*/ .a{color:blue;}/*!sc*/ data-styled.g2[id="TWO"]{content:"a,"}/*!sc*/ </style> `; exports[`ssr should return a generated React style element 1`] = ` { "dangerouslySetInnerHTML": { "__html": "body{background:papayawhip;}/*!sc*/ data-styled.g1[id="sc-global-a1"]{content:"sc-global-a1,"}/*!sc*/ .c{color:red;}/*!sc*/ data-styled.g2[id="sc-b"]{content:"c,"}/*!sc*/ ", }, "data-styled": "", "data-styled-version": "JEST_MOCK_VERSION", } `; exports[`ssr should throw if getStyleElement is called after interleaveWithNodeStream is called 1`] = ` "Can't collect styles once you've consumed a \`ServerStyleSheet\`'s styles! \`ServerStyleSheet\` is a one off instance for each server-side render cycle. - Are you trying to reuse it across renders? - Are you accidentally calling collectStyles twice?" `; exports[`ssr should throw if getStyleElement is called after streaming is complete 1`] = ` <style data-styled="true" data-styled-version="JEST_MOCK_VERSION" > body{background:papayawhip;}/*!sc*/ data-styled.g1[id="sc-global-a1"]{content:"sc-global-a1,"}/*!sc*/ .c{color:red;}/*!sc*/ data-styled.g2[id="sc-b"]{content:"c,"}/*!sc*/ </style> <h1 class="sc-b c"> Hello SSR! </h1> `; exports[`ssr should throw if getStyleElement is called after streaming is complete 2`] = ` "Can't collect styles once you've consumed a \`ServerStyleSheet\`'s styles! \`ServerStyleSheet\` is a one off instance for each server-side render cycle. - Are you trying to reuse it across renders? - Are you accidentally calling collectStyles twice?" `; exports[`ssr should throw if getStyleTags is called after interleaveWithNodeStream is called 1`] = ` "Can't collect styles once you've consumed a \`ServerStyleSheet\`'s styles! \`ServerStyleSheet\` is a one off instance for each server-side render cycle. - Are you trying to reuse it across renders? - Are you accidentally calling collectStyles twice?" `; exports[`ssr should throw if getStyleTags is called after streaming is complete 1`] = ` <style data-styled="true" data-styled-version="JEST_MOCK_VERSION" > body{background:papayawhip;}/*!sc*/ data-styled.g1[id="sc-global-a1"]{content:"sc-global-a1,"}/*!sc*/ .c{color:red;}/*!sc*/ data-styled.g2[id="sc-b"]{content:"c,"}/*!sc*/ </style> <h1 class="sc-b c"> Hello SSR! </h1> `; exports[`ssr should throw if getStyleTags is called after streaming is complete 2`] = ` "Can't collect styles once you've consumed a \`ServerStyleSheet\`'s styles! \`ServerStyleSheet\` is a one off instance for each server-side render cycle. - Are you trying to reuse it across renders? - Are you accidentally calling collectStyles twice?" `; exports[`ssr should throw if interleaveWithNodeStream is called twice 1`] = ` "Can't collect styles once you've consumed a \`ServerStyleSheet\`'s styles! \`ServerStyleSheet\` is a one off instance for each server-side render cycle. - Are you trying to reuse it across renders? - Are you accidentally calling collectStyles twice?" `;
3,080
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/test
petrpan-code/styled-components/styled-components/packages/styled-components/src/test/__snapshots__/theme.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`theming should not allow the theme to be a non-object 1`] = `"ThemeProvider: Please make your "theme" prop an object."`; exports[`theming should not allow the theme to be an array 1`] = `"ThemeProvider: Please make your "theme" prop an object."`; exports[`theming should not allow the theme to be null 1`] = `"ThemeProvider: "theme" prop is required."`;
3,111
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/addUnitIfNeeded.test.ts
import addUnitIfNeeded from '../addUnitIfNeeded'; it('adds a px prefix if needed for properties that require a unit', () => { const pairs: Array<[string, number]> = [ ['marginLeft', 1], ['top', -1], ['flexBasis', 100], ['gridTemplateColumns', 200], ['fontSize', 10], ]; pairs.forEach(([key, value]) => expect(addUnitIfNeeded(key, value)).toEqual(`${value}px`)); }); it('does not add a px prefix for unitless properties', () => { const pairs: Array<[string, number]> = [ ['lineHeight', 1], ['flex', 2], ['fontWeight', 400], ['--tooltip-z-index', 1000], ]; pairs.forEach(([key, value]) => expect(addUnitIfNeeded(key, value)).toEqual(String(value))); });
3,112
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/determineTheme.test.ts
import determineTheme from '../determineTheme'; const theme = { color: 'red' }; const fallback = { color: 'blue' }; const props = { theme }; const defaultProps = { theme: fallback }; describe('determineTheme', () => { it('should take precedence over ThemeProvider', () => { expect(determineTheme(props, fallback, defaultProps)).toEqual(theme); }); it('should fallback to default theme', () => { expect(determineTheme({}, fallback, props)).toEqual(fallback); }); it('should be undefined when no theme is passed', () => { expect(determineTheme({}, undefined, undefined)).toEqual(undefined); }); });
3,113
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/error.test.ts
import styledError from '../error'; describe('development', () => { it('returns a rich error', () => { expect(() => { throw styledError(2); }).toThrowErrorMatchingInlineSnapshot(` "Can't collect styles once you've consumed a \`ServerStyleSheet\`'s styles! \`ServerStyleSheet\` is a one off instance for each server-side render cycle. - Are you trying to reuse it across renders? - Are you accidentally calling collectStyles twice?" `); }); it('allows interpolation', () => { expect(() => { throw styledError(1, 'foo'); }).toThrowErrorMatchingInlineSnapshot(`"Cannot create styled-component for component: foo."`); }); }); describe('production', () => { beforeEach(() => { process.env.NODE_ENV = 'production'; }); it('returns an error link', () => { expect(() => { throw styledError(2); }).toThrowErrorMatchingInlineSnapshot( `"An error occurred. See https://github.com/styled-components/styled-components/blob/main/packages/styled-components/src/utils/errors.md#2 for more information."` ); }); it('returns an error link with interpolations if given', () => { expect(() => { throw styledError(1, 'foo'); }).toThrowErrorMatchingInlineSnapshot( `"An error occurred. See https://github.com/styled-components/styled-components/blob/main/packages/styled-components/src/utils/errors.md#1 for more information. Args: foo"` ); }); });
3,114
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/escape.test.ts
import escape from '../escape'; describe('escape', () => { it('replaces characters that could be part of CSS selectors', () => { expect(escape('foo(bar):#*$><+~=|^baz')).toEqual('foo-bar-baz'); }); it('replaces double hyphens with a single hyphen', () => { expect(escape('foo--bar')).toEqual('foo-bar'); }); it('removes extraneous hyphens at the ends of the string', () => { expect(escape('-foo--bar-')).toEqual('foo-bar'); }); });
3,115
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/flatten.test.tsx
import React from 'react'; import TestRenderer from 'react-test-renderer'; import styled from '../../constructors/styled'; import flatten from '../flatten'; describe('flatten', () => { it('doesnt merge strings', () => { expect(flatten(['foo', 'bar', 'baz'])).toEqual(['foo', 'bar', 'baz']); }); it('drops nulls', () => { expect(flatten(['foo', false, 'bar', undefined, 'baz', null])).toEqual(['foo', 'bar', 'baz']); }); it('doesnt drop any numbers', () => { expect(flatten(['foo', 0, 'bar', NaN, 'baz', -1])).toEqual([ 'foo', '0', 'bar', 'NaN', 'baz', '-1', ]); }); it('toStrings everything', () => { // @ts-expect-error invalid input test expect(flatten([1, true])).toEqual(['1', 'true']); }); it('hypenates objects', () => { const obj = { fontSize: 14, lineHeight: '15px', WebkitFilter: 'blur(2px)', fontWeight: 500, }; const css = [ 'font-size: 14px;', 'line-height: 15px;', '-webkit-filter: blur(2px);', 'font-weight: 500;', ]; expect(flatten([obj])).toEqual(css); expect(flatten(['some:thing;', obj, 'something: else;'])).toEqual([ 'some:thing;', ...css, 'something: else;', ]); }); it('handles nested objects', () => { const obj = { fontSize: '14px', '@media screen and (min-width: 250px)': { fontSize: '16px', }, '&:hover': { fontWeight: 'bold', }, }; const css = [ 'font-size: 14px;', '@media screen and (min-width: 250px) {', 'font-size: 16px;', '}', '&:hover {', 'font-weight: bold;', '}', ]; expect(flatten([obj])).toEqual(css); expect(flatten(['some:thing;', obj, 'something: else;'])).toEqual([ 'some:thing;', ...css, 'something: else;', ]); }); it('toStrings class instances', () => { class SomeClass { toString() { return 'some: thing;'; } } // This works but we don't support it directly in the Interpolation type, // because it prevents generating type errors that we usually want. // @ts-expect-error properly catching unexpected class instance expect(flatten([new SomeClass()])).toEqual(['some: thing;']); }); it('flattens subarrays', () => { expect(flatten([1, 2, [3, 4, 5], 'come:on;', 'lets:ride;'])).toEqual([ '1', '2', '3', '4', '5', 'come:on;', 'lets:ride;', ]); }); it('defers functions', () => { const func = () => 'bar'; const funcWFunc = () => ['static', (subfunc: Function) => (subfunc ? 'bar' : 'baz')]; expect(flatten(['foo', func, 'baz'])).toEqual(['foo', func, 'baz']); expect(flatten(['foo', funcWFunc, 'baz'])).toEqual(['foo', funcWFunc, 'baz']); }); it('executes functions', () => { const func = () => 'bar'; expect(flatten(['foo', func, 'baz'], { bool: true, theme: {} })).toEqual(['foo', 'bar', 'baz']); }); it('passes values to function', () => { const func = ({ bool }: any) => (bool ? 'bar' : 'baz'); expect(flatten(['foo', func], { bool: true, theme: {} })).toEqual(['foo', 'bar']); expect(flatten(['foo', func], { bool: false, theme: {} })).toEqual(['foo', 'baz']); }); it('recursively calls functions', () => { const func = () => ['static', ({ bool }: any) => (bool ? 'bar' : 'baz')]; expect(flatten(['foo', func], { bool: true } as any)).toEqual(['foo', 'static', 'bar']); expect(flatten(['foo', func], { bool: false } as any)).toEqual(['foo', 'static', 'baz']); }); it('throws if trying to interpolate a normal React component', () => { jest.spyOn(console, 'error').mockImplementation(() => {}); const Foo = ({ className }: { className?: string }) => ( <div className={className}>hello there!</div> ); const Bar = styled.div` ${ // @ts-expect-error invalid input Foo }: { background-color: red; } `; TestRenderer.create(<Bar />); expect((console.error as jest.Mock<Console['warn']>).mock.calls[0][0]).toMatchInlineSnapshot( `"Foo is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details."` ); }); it('does not error for regular functions', () => { jest.spyOn(console, 'error').mockImplementation(() => {}); const SvgIcon = styled.svg` vertical-align: middle; height: ${props => (props.height ? `${props.height}px` : '22px')}; width: ${props => (props.width ? `${props.width}px` : '22px')}; text-align: center; font-size: 40px; `; expect(() => TestRenderer.create( <SvgIcon viewBox="0 0 512 512"> <path d="M39.6,95.6z" /> </SvgIcon> ) ).not.toThrowError(); expect(console.error).not.toHaveBeenCalled(); }); }); it('does not error for functions that return null', () => { jest.spyOn(console, 'error').mockImplementation(() => {}); const Bar = styled.div` ${() => null} `; expect(() => TestRenderer.create(<Bar />)).not.toThrowError(); expect(console.error).not.toHaveBeenCalled(); });
3,116
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/generateAlphabeticName.test.ts
import generateAlphabeticName from '../generateAlphabeticName'; describe('generateAlphabeticName', () => { it('should create alphabetic names for number input data', () => { expect(generateAlphabeticName(1000000000)).toEqual('cGNYzm'); expect(generateAlphabeticName(2000000000)).toEqual('fnBWYy'); }); it('should not fail for numbers above int32 limit', () => { expect(generateAlphabeticName(3819806601)).toEqual('kcwstn'); }); it('breaks up substrings of "ad" case-insensitive to avoid adblocker issues', () => { expect(generateAlphabeticName(1355)).toMatchInlineSnapshot(`"A-d"`); expect(generateAlphabeticName(1381)).toMatchInlineSnapshot(`"A-D"`); expect(generateAlphabeticName(2707)).toMatchInlineSnapshot(`"a-d"`); expect(generateAlphabeticName(2733)).toMatchInlineSnapshot(`"a-D"`); expect(generateAlphabeticName(7390035)).toMatchInlineSnapshot(`"a-Da-d"`); }); });
3,117
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/generateDisplayName.test.ts
import React from 'react'; import generateDisplayName from '../generateDisplayName'; it('handles a string type', () => { expect(generateDisplayName('div')).toBe('styled.div'); }); it('handles a React class type', () => { class Foo extends React.Component {} expect(generateDisplayName(Foo)).toBe('Styled(Foo)'); }); it('handles a React class type with displayName', () => { class Foo extends React.Component { static displayName = 'Bar'; } expect(generateDisplayName(Foo)).toBe('Styled(Bar)'); });
3,118
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/getComponentName.test.tsx
import React from 'react'; import getComponentName from '../getComponentName'; describe('getComponentName', () => { let Test: React.FC; beforeEach(() => { Test = () => <div />; }); it('defaults to reusing the component displayName', () => { Test.displayName = 'Foo'; expect(getComponentName(Test)).toEqual('Foo'); }); it('falls back to the class name', () => { expect(getComponentName(Test)).toEqual('Test'); }); it('ultimately falls back to "Component"', () => { Object.defineProperty(Test, 'name', { value: '', }); expect(getComponentName(Test)).toEqual('Component'); }); });
3,119
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/hyphenateStyleName.test.ts
import hyphenateStyleName from '../hyphenateStyleName'; test('hyphenateStyleName', () => { expect(hyphenateStyleName('backgroundColor')).toEqual('background-color'); expect(hyphenateStyleName('MozTransition')).toEqual('-moz-transition'); expect(hyphenateStyleName('msTransition')).toEqual('-ms-transition'); // https://github.com/styled-components/styled-components/issues/3810 expect(hyphenateStyleName('--MyColor')).toEqual('--MyColor'); });
3,120
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/interleave.test.ts
import interleave from '../interleave'; describe('interleave', () => { it('blindly interleave', () => { expect(interleave([], [])).toEqual([undefined]); expect(interleave(['foo'], [])).toEqual(['foo']); expect(interleave(['foo'], [1])).toEqual(['foo', 1, undefined]); expect(interleave(['foo', 'bar'], [1])).toEqual(['foo', 1, 'bar']); }); it('should be driven off the number of interpolations', () => { expect(interleave(['foo', 'bar'], [])).toEqual(['foo']); expect(interleave(['foo', 'bar', 'baz'], [1])).toEqual(['foo', 1, 'bar']); expect(interleave([], [1])).toEqual([undefined, 1, undefined]); expect(interleave(['foo'], [1, 2, 3])).toEqual([ 'foo', 1, undefined, 2, undefined, 3, undefined, ]); }); });
3,121
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/isPlainObject.test.ts
import React from 'react'; import vm from 'vm'; import isPlainObject from '../isPlainObject'; it('returns true for an object literal', () => { expect(isPlainObject({})).toEqual(true); }); it('returns false for an instance of a class with its own toString method', () => { class SomeClass { toString() { return 'some: thing;'; } } expect(isPlainObject(new SomeClass())).toEqual(false); }); it('returns false for an instance of an object with a custom prototype', () => { class SomeObj {} expect(isPlainObject(new SomeObj())).toEqual(false); }); it('returns false for a function', () => { expect(isPlainObject(() => {})).toEqual(false); }); it('returns false for an array', () => { expect(isPlainObject([])).toEqual(false); }); it('returns false for a React component', () => { class Foo extends React.Component {} expect(isPlainObject(Foo)).toEqual(false); }); it('returns false for a React element', () => { expect(isPlainObject(React.createElement('div'))).toEqual(false); }); it('returns true for an object literal created in a different context', () => { const context = vm.createContext({}); vm.runInContext('object = {};', context); expect(isPlainObject(context.object)).toEqual(true); });
3,122
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/isStatelessFunction.test.tsx
import React, { Component } from 'react'; import styled from '../../'; import isStatelessFunction from '../isStatelessFunction'; class MockComponent extends Component { render() { return <div {...this.props} />; } } describe('isStatelessFunction(something)', () => { it('returns true if stateless', () => { expect(isStatelessFunction(() => {})).toBe(true); }); it('returns false for everything else', () => { expect(isStatelessFunction(styled.div``)).toBe(false); expect(isStatelessFunction(MockComponent)).toBe(false); expect(isStatelessFunction({})).toBe(false); expect(isStatelessFunction([])).toBe(false); }); });
3,123
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/isStyledComponent.test.ts
import React from 'react'; import styled from '../../'; import isStyledComponent from '../isStyledComponent'; describe('isStyledComponent(something)', () => { it('returns true if using styled', () => { expect(isStyledComponent(styled.div``)).toBe(true); expect(isStyledComponent(styled(styled.div``)``)).toBe(true); }); it('returns false for everything else', () => { [() => {}, class Foo extends React.Component {}, 'foo', 1234, true, false].forEach(test => expect(isStyledComponent(test)).toBe(false) ); }); });
3,124
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/joinStrings.test.ts
import { joinStringArray, joinStrings } from '../joinStrings'; describe('joinStrings(string?, string?)', () => { it('joins the two strings with a space between', () => { expect(joinStrings('a', 'b')).toBe('a b'); expect(joinStrings('a ', 'b')).toBe('a b'); expect(joinStrings('a ', ' b')).toBe('a b'); }); it('ignores falsy inputs', () => { expect(joinStrings('a')).toBe('a'); expect(joinStrings('a', null)).toBe('a'); expect(joinStrings('a', '')).toBe('a'); expect(joinStrings(null, 'b')).toBe('b'); expect(joinStrings('', 'b')).toBe('b'); }); }); describe('joinStringArray(string[], string?)', () => { it('joins the strings with the separator between', () => { expect(joinStringArray(['a', 'b'], ' ')).toBe('a b'); expect(joinStringArray(['a ', 'b'], ' ')).toBe('a b'); expect(joinStringArray(['a ', ' b'], ' ')).toBe('a b'); }); it('joins the strings with no separator when separator is falsy', () => { expect(joinStringArray(['a', 'b'])).toBe('ab'); expect(joinStringArray(['a', 'b'], '')).toBe('ab'); }); it('returns the string unmodified if only one in array', () => { expect(joinStringArray(['a'])).toBe('a'); expect(joinStringArray(['a'], ' ')).toBe('a'); }); it('returns an empty string for an empty array', () => { expect(joinStringArray([])).toBe(''); }); });
3,125
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/mixinDeep.test.ts
/* ported from https://github.com/jonschlinkert/mixin-deep; thanks Jon! */ import mixinDeep from '../mixinDeep'; class MyObj { foo: any; bar: any; baz?: 5; constructor(foo: any, bar: any, baz: any = undefined) { this.foo = foo; this.bar = bar; if (baz) { this.baz = 5; } } } it('should deeply mix the properties of object into the first object.', () => { expect(mixinDeep({ a: { aa: 'aa' } }, { a: { bb: 'bb' } }, { a: { cc: 'cc' } })).toEqual({ a: { aa: 'aa', bb: 'bb', cc: 'cc' }, }); expect( mixinDeep( { a: { aa: 'aa', dd: { ee: 'ff' } } }, { a: { bb: 'bb', dd: { gg: 'hh' } } }, { a: { cc: 'cc', dd: { ii: 'jj' } } } ) ).toEqual({ a: { aa: 'aa', dd: { ee: 'ff', gg: 'hh', ii: 'jj' }, bb: 'bb', cc: 'cc' } }); }); it('should copy properties onto the first object', () => { const obj1 = { a: 0, b: 1 }; const obj2 = { c: 2, d: 3 }; const obj3 = { a: 4, d: 5 }; const actual = { a: 4, b: 1, c: 2, d: 5 }; expect(mixinDeep({}, obj1, obj2, obj3)).toEqual(actual); expect(actual).not.toEqual(obj1); expect(actual).not.toEqual(obj2); expect(actual).not.toEqual(obj3); }); it('should mixin nested object properties', () => { const obj1 = { a: { b: 1, c: 1, d: { e: 1, f: 1 } } }; const obj2 = { a: { b: 2, d: { f: 'f' } } }; expect(mixinDeep(obj1, obj2)).toEqual({ a: { b: 2, c: 1, d: { e: 1, f: 'f' } } }); }); it('should shallow merge properties if target is not a POJO or array', () => { const obj1 = new MyObj(5, 6); const obj2 = { a: { b: 2, d: { f: 'f' } } }; expect(mixinDeep(obj1, obj2)).toMatchInlineSnapshot(` MyObj { "a": { "b": 2, "d": { "f": "f", }, }, "bar": 6, "foo": 5, } `); }); it('should NOT shallow merge non-POJO properties of target', () => { const obj1 = { wrapped: new MyObj(5, 6) }; const obj2 = { wrapped: { a: { b: 2, d: { f: 'f' } } } }; expect(mixinDeep(obj1, obj2)).toEqual({ wrapped: { a: { b: 2, d: { f: 'f' } } } }); }); it('should use the last value defined', () => { const obj1 = { a: 'b' }; const obj2 = { a: 'c' }; expect(mixinDeep(obj1, obj2)).toEqual({ a: 'c' }); }); it('should use the last value defined on nested object', () => { const obj1 = { a: 'b', c: { d: 'e' } }; const obj2 = { a: 'c', c: { d: 'f' } }; expect(mixinDeep(obj1, obj2)).toEqual({ a: 'c', c: { d: 'f' } }); }); it('should shallow mixin when an empty object is passed', () => { const obj1 = { a: 'b', c: { d: 'e' } }; const obj2 = { a: 'c', c: { d: 'f' } }; expect(mixinDeep({}, obj1, obj2)).toEqual({ a: 'c', c: { d: 'f' } }); }); it('should mixin additional objects into the first:', () => { const obj1 = { a: { b: 1, c: 1, d: { e: 1, f: 1 } } }; const obj2 = { a: { b: 2, d: { f: 'f' } } }; mixinDeep(obj1, obj2); expect(obj1).toEqual({ a: { b: 2, c: 1, d: { e: 1, f: 'f' } } }); }); it('should mixin objects during mixin', () => { const obj1 = { a: { b: 1 } }; const obj2 = { a: { c: 2 } }; const actual = mixinDeep({}, obj1, obj2); expect(actual).toEqual({ a: { b: 1, c: 2 } }); expect(actual.a).toEqual(obj1.a); expect(actual.a).not.toEqual(obj2.a); }); it('should deep mixin arrays during mixin', () => { const obj1 = { a: [1, 2, [3, 4]] }; const obj2 = { b: [5, 6] }; const actual = mixinDeep(obj1, obj2); expect(actual.a).toEqual([1, 2, [3, 4]]); expect(actual.a[2]).toEqual([3, 4]); expect(actual.b).toEqual(obj2.b); expect( mixinDeep( [new MyObj(1, 2), { a: 1 }, new MyObj(4, 5), new MyObj(8, 9)], [{ abc: 345 }, { abc: 456 }, new MyObj(7, 8)] ) ).toMatchInlineSnapshot(` [ { "abc": 345, }, { "a": 1, "abc": 456, }, MyObj { "bar": 8, "foo": 7, }, MyObj { "bar": 9, "foo": 8, }, ] `); }); it('should not modify source properties', () => { expect(mixinDeep({ test: true }).test).toEqual(true); }); it('should properly mixin arrays', () => { expect(mixinDeep([1, 2, 3])).toEqual([1, 2, 3]); expect(mixinDeep([1, 2, 3], {})).toEqual([1, 2, 3]); expect(mixinDeep([1, 2, 3], {})).toEqual([1, 2, 3]); expect(mixinDeep([10, 20, 30, 40, 50, 60], [11, 21, { abc: 123 }, true], [12, 22])).toEqual([ 12, 22, { abc: 123 }, true, 50, 60, ]); expect(mixinDeep([10], [11, 21, { abc: 123 }, true], [12, 22])).toEqual([ 12, 22, { abc: 123 }, true, ]); }); it('should work with sparse objects:', () => { const actual = mixinDeep({}, undefined, { a: 'b' }, undefined, { c: 'd' }); expect(actual).toEqual({ a: 'b', c: 'd' }); }); it('should mixin RegExps', () => { const fixture = /test/g; const actual = mixinDeep(fixture); expect(actual).toEqual(fixture); }); it('should mixin Dates', () => { const fixture = new Date(); const actual = mixinDeep(fixture); expect(actual).toEqual(fixture); }); it('should not mixin objects created with custom constructor', () => { class TestType {} const fixture = new TestType(); const actual = mixinDeep(fixture); expect(actual).toEqual(fixture); }); it('should not fail on objects with cyclical prototypes', () => { const Cyclical = function () {}; // @ts-expect-error properly catching hacky test JS Cyclical.prototype.cycle = new Cyclical(); // @ts-expect-error properly catching hacky test JS const cycle1 = new Cyclical(); // @ts-expect-error properly catching hacky test JS const cycle2 = new Cyclical(); const actual = mixinDeep(cycle1, cycle2, { a: 1 }); expect(actual).toEqual(cycle1); });
3,126
0
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils
petrpan-code/styled-components/styled-components/packages/styled-components/src/utils/test/stylis.test.ts
import createStylisInstance, { ICreateStylisInstance } from '../stylis'; function stylisTest(css: string, options: ICreateStylisInstance = {}): string[] { const stylis = createStylisInstance(options); const componentId = 'a'; return stylis(css, `.${componentId}`, undefined, componentId); } describe('stylis', () => { it('handles simple rules', () => { const css = stylisTest(` background: yellow; color: red; `); expect(css).toMatchInlineSnapshot(` [ ".a{background:yellow;color:red;}", ] `); }); it('splits css with multiple rules', () => { const css = stylisTest(` background: yellow; color: red; @media (min-width: 500px) { color: blue; } `); expect(css).toMatchInlineSnapshot(` [ ".a{background:yellow;color:red;}", "@media (min-width: 500px){.a{color:blue;}}", ] `); }); it('splits css with encoded closing curly brace', () => { const css = stylisTest(` @media (min-width: 500px) { &::before { content: "}"; } } `); expect(css).toMatchInlineSnapshot(` [ "@media (min-width: 500px){.a::before{content:"}";}}", ] `); }); it('splits vendor-prefixed rules', () => { const css = stylisTest( ` &::placeholder { color: red; } // this currently does not split correctly @media (min-width: 500px) { &::placeholder { content: "}"; } } `, { options: { prefix: true } } ); expect(css).toMatchInlineSnapshot(` [ ".a::-webkit-input-placeholder{color:red;}", ".a::-moz-placeholder{color:red;}", ".a:-ms-input-placeholder{color:red;}", ".a::placeholder{color:red;}", "@media (min-width: 500px){.a::-webkit-input-placeholder{content:"}";}}", "@media (min-width: 500px){.a::-moz-placeholder{content:"}";}}", "@media (min-width: 500px){.a:-ms-input-placeholder{content:"}";}}", "@media (min-width: 500px){.a::placeholder{content:"}";}}", ] `); }); });
3,815
0
petrpan-code/TanStack/query/packages/eslint-plugin-query/src
petrpan-code/TanStack/query/packages/eslint-plugin-query/src/__tests__/configs.test.ts
import { describe, expect, it } from 'vitest' import { configs } from '../configs' describe('configs', () => { it('should match snapshot', () => { expect(configs).toMatchInlineSnapshot(` { "recommended": { "plugins": [ "@tanstack/eslint-plugin-query", ], "rules": { "@tanstack/query/exhaustive-deps": "error", "@tanstack/query/no-rest-destructuring": "warn", "@tanstack/query/stable-query-client": "error", }, }, } `) }) })
3,816
0
petrpan-code/TanStack/query/packages/eslint-plugin-query/src
petrpan-code/TanStack/query/packages/eslint-plugin-query/src/__tests__/exhaustive-deps.test.ts
import { ESLintUtils } from '@typescript-eslint/utils' import { normalizeIndent } from '../utils/test-utils' import { rule } from '../rules/exhaustive-deps.rule' const ruleTester = new ESLintUtils.RuleTester({ parser: '@typescript-eslint/parser', settings: {}, }) ruleTester.run('exhaustive-deps', rule, { valid: [ { name: 'should pass when deps are passed in array (react)', code: 'useQuery({ queryKey: ["todos"], queryFn: fetchTodos });', }, { name: 'should pass when deps are passed in array (solid)', code: 'createQuery({ queryKey: ["todos"], queryFn: fetchTodos });', }, { name: 'should pass when deps are passed in array', code: 'useQuery({ queryKey: ["entity", id], queryFn: () => api.getEntity(id) });', }, { name: 'should pass when deps are passed in template literal', // eslint-disable-next-line no-template-curly-in-string code: 'useQuery({ queryKey: [`entity/${id}`], queryFn: () => api.getEntity(id) });', }, { name: 'should not pass fetch', code: 'useQuery({ queryKey: ["entity", id], queryFn: () => fetch(id) });', }, { name: 'should not pass axios.get', code: 'useQuery({ queryKey: ["entity", id], queryFn: () => axios.get(id) });', }, { name: 'should not pass api.entity.get', code: 'useQuery({ queryKey: ["entity", id], queryFn: () => api.entity.get(id) });', }, { name: 'should not pass api when is being used for calling a function', code: ` import useApi from './useApi' const useFoo = () => { const api = useApi(); return useQuery({ queryKey: ['foo'], queryFn: () => api.fetchFoo(), }) } `, }, { name: 'should pass props.src', code: ` function MyComponent(props) { useQuery({ queryKey: ["entity", props.src], queryFn: () => api.entity.get(props.src) }); } `, }, { name: 'identify !!props.id (unary expression)', code: ` function MyComponent(props) { useQuery({ queryKey: ["entity", !!props.id], queryFn: () => api.entity.get(props.id) }); } `, }, { name: 'identify props?.id (chain expression)', code: ` function MyComponent(props) { useQuery({ queryKey: ["entity", props?.id], queryFn: () => api.entity.get(props?.id) }); } `, }, { name: 'identify props!.id (ts non null expression)', code: ` function MyComponent(props) { useQuery({ queryKey: ["entity", props!.id], queryFn: () => api.entity.get(props!.id) }); } `, }, { name: 'should ignore keys from callback', code: ` function MyComponent(props) { useQuery({ queryKey: ["foo", dep1], queryFn: ({ queryKey: [, dep] }) => fetch(dep), }); } `, }, { name: 'should ignore type identifiers', code: ` type Result = {}; function MyComponent(props) { useQuery({ queryKey: ["foo", dep], queryFn: () => api.get<Result>(dep), }); } `, }, { name: 'should add "...args" to deps', code: ` function foo(...args) {} function useData(arg, ...args) { return useQuery({ queryKey: ['foo', arg, ...args], queryFn: async () => foo([arg, ...args]) }); } `, }, { name: 'should not add class to deps', code: ` class Foo {} useQuery({ queryKey: ['foo'], queryFn: async () => new Foo() }); `, }, { name: 'should not add `undefined` to deps', code: ` useQuery({ queryKey: [], queryFn: async () => { if (undefined) { return null; } return 1 }, }); `, }, { name: 'should not fail when queryKey is a queryKeyFactory while having a dep as first arg', code: normalizeIndent` const fooQueryKeyFactory = { foo: () => ['foo'] as const, num: (num: number) => [...fooQueryKeyFactory.foo(), num] as const, } const useFoo = (num: number) => useQuery({ queryKey: fooQueryKeyFactory.foo(num), queryFn: () => Promise.resolve(num), }) `, }, { name: 'should not fail when queryKey is a queryKeyFactory while having a dep in object', code: normalizeIndent` const fooQueryKeyFactory = { foo: () => ['foo'] as const, num: (num: number) => [...fooQueryKeyFactory.foo(), num] as const, } const useFoo = (num: number) => useQuery({ queryKey: fooQueryKeyFactory.foo({ x: num }), queryFn: () => Promise.resolve(num), }) `, }, { name: 'should not fail when queryKey is a queryKeyFactory while having a dep in object 2', code: normalizeIndent` const fooQueryKeyFactory = { foo: () => ['foo'] as const, num: (num: number) => [...fooQueryKeyFactory.foo(), num] as const, } const useFoo = (num: number) => useQuery({ queryKey: fooQueryKeyFactory.foo({ num }), queryFn: () => Promise.resolve(num), }) `, }, { name: 'should not fail when queryKey is a queryKeyFactory while having a dep in array', code: normalizeIndent` const fooQueryKeyFactory = { foo: () => ['foo'] as const, num: (num: number) => [...fooQueryKeyFactory.foo(), num] as const, } const useFoo = (num: number) => useQuery({ queryKey: fooQueryKeyFactory.foo([num]), queryFn: () => Promise.resolve(num), }) `, }, { name: 'should not fail when queryKey is a queryKeyFactory while having a dep in second arg', code: normalizeIndent` const fooQueryKeyFactory = { foo: () => ['foo'] as const, num: (num: number) => [...fooQueryKeyFactory.foo(), num] as const, } const useFoo = (num: number) => useQuery({ queryKey: fooQueryKeyFactory.foo(1, num), queryFn: () => Promise.resolve(num), }) `, }, { name: 'should not fail when queryKey is a queryKeyFactory while having a dep is object prop', code: normalizeIndent` const fooQueryKeyFactory = { foo: () => ['foo'] as const, num: (num: number) => [...fooQueryKeyFactory.foo(), num] as const, } const useFoo = (obj: { num: number }) => useQuery({ queryKey: fooQueryKeyFactory.foo(obj.num), queryFn: () => Promise.resolve(obj.num), }) `, }, { name: 'should not treat new Error as missing dependency', code: normalizeIndent` useQuery({ queryKey: ['foo'], queryFn: () => Promise.reject(new Error('1')), }) `, }, { name: 'should see id when there is a const assertion', code: normalizeIndent` const useX = (id: number) => { return useQuery({ queryKey: ['foo', id] as const, queryFn: async () => id, }) } `, }, { name: 'should not fail if queryKey is having the whole object while queryFn uses some props of it', code: normalizeIndent` const state = { foo: 'foo', bar: 'bar' } useQuery({ queryKey: ['state', state], queryFn: () => Promise.resolve({ foo: state.foo, bar: state.bar }) }) `, }, { name: 'should not fail if queryKey does not include an internal dependency', code: normalizeIndent` useQuery({ queryKey: ["api"], queryFn: async () => { const response = Promise.resolve([]); const data = await response.json(); return data[0].name; }, }); `, }, { name: 'should ignore constants defined out of scope (react component, function declaration)', code: ` const CONST_VAL = 1 function MyComponent() { useQuery({ queryKey: ["foo"], queryFn: () => CONST_VAL }); } `, }, { name: 'should ignore constants defined out of scope (react component, function expression)', code: ` const CONST_VAL = 1 const MyComponent = () => { useQuery({ queryKey: ["foo"], queryFn: () => CONST_VAL }); } `, }, { name: 'should ignore constants defined out of scope (react component, anonymous function)', code: ` const CONST_VAL = 1 const MyComponent = function () { useQuery({ queryKey: ["foo"], queryFn: () => CONST_VAL }); } `, }, { name: 'should ignore constants defined out of scope (non react component/hook function)', code: ` const CONST_VAL = 1 function fn() { return { queryKey: ["foo"], queryFn: () => CONST_VAL } } `, }, { name: 'should ignore constants defined out of scope (react hook, function declaration)', code: ` const CONST_VAL = 1 function useHook() { useQuery({ queryKey: ["foo"], queryFn: () => CONST_VAL }); } `, }, { name: 'should ignore constants defined out of scope (react hook, function expression)', code: ` const CONST_VAL = 1 const useHook = () => { useQuery({ queryKey: ["foo"], queryFn: () => CONST_VAL }); } `, }, { name: 'should ignore constants defined out of scope (react hook, anonymous function)', code: ` const CONST_VAL = 1 const useHook = function () { useQuery({ queryKey: ["foo"], queryFn: () => CONST_VAL }); } `, }, { name: 'should ignore references of the queryClient', code: ` const CONST_VAL = 1 function useHook() { const queryClient = useQueryClient() const kueryKlient = useQueryClient() useQuery({ queryKey: ["foo"], queryFn: () => { doSomething(queryClient) queryClient.invalidateQueries() doSomethingSus(kueryKlient) } }); } `, }, ], invalid: [ { name: 'should fail when deps are missing in query factory', code: normalizeIndent` const todoQueries = { list: () => ({ queryKey: ['entity'], queryFn: fetchEntities }), detail: (id) => ({ queryKey: ['entity'], queryFn: () => fetchEntity(id) }) } `, errors: [ { messageId: 'missingDeps', data: { deps: 'id' }, suggestions: [ { messageId: 'fixTo', data: { result: "['entity', id]" }, output: normalizeIndent` const todoQueries = { list: () => ({ queryKey: ['entity'], queryFn: fetchEntities }), detail: (id) => ({ queryKey: ['entity', id], queryFn: () => fetchEntity(id) }) } `, }, ], }, ], }, { name: 'should fail when no deps are passed (react)', code: normalizeIndent` const id = 1; useQuery({ queryKey: ["entity"], queryFn: () => api.getEntity(id) }); `, errors: [ { messageId: 'missingDeps', data: { deps: 'id' }, suggestions: [ { messageId: 'fixTo', data: { result: '["entity", id]' }, output: normalizeIndent` const id = 1; useQuery({ queryKey: ["entity", id], queryFn: () => api.getEntity(id) }); `, }, ], }, ], }, { name: 'should fail when no deps are passed (solid)', code: normalizeIndent` const id = 1; createQuery({ queryKey: ["entity"], queryFn: () => api.getEntity(id) }); `, errors: [ { messageId: 'missingDeps', data: { deps: 'id' }, suggestions: [ { messageId: 'fixTo', data: { result: '["entity", id]' }, output: normalizeIndent` const id = 1; createQuery({ queryKey: ["entity", id], queryFn: () => api.getEntity(id) }); `, }, ], }, ], }, { name: 'should fail when deps are passed incorrectly', code: normalizeIndent` const id = 1; useQuery({ queryKey: ["entity/\${id}"], queryFn: () => api.getEntity(id) }); `, errors: [ { messageId: 'missingDeps', data: { deps: 'id' }, suggestions: [ { messageId: 'fixTo', // eslint-disable-next-line no-template-curly-in-string data: { result: '["entity/${id}", id]' }, output: normalizeIndent` const id = 1; useQuery({ queryKey: ["entity/\${id}", id], queryFn: () => api.getEntity(id) }); `, }, ], }, ], }, { name: 'should pass missing dep while key has a template literal', code: normalizeIndent` const a = 1; const b = 2; useQuery({ queryKey: [\`entity/\${a}\`], queryFn: () => api.getEntity(a, b) }); `, errors: [ { messageId: 'missingDeps', data: { deps: 'b' }, suggestions: [ { messageId: 'fixTo', // eslint-disable-next-line no-template-curly-in-string data: { result: '[`entity/${a}`, b]' }, output: normalizeIndent` const a = 1; const b = 2; useQuery({ queryKey: [\`entity/\${a}\`, b], queryFn: () => api.getEntity(a, b) }); `, }, ], }, ], }, { name: 'should fail when dep exists inside setter and missing in queryKey', code: normalizeIndent` const [id] = React.useState(1); useQuery({ queryKey: ["entity"], queryFn: () => { const { data } = axios.get(\`.../\${id}\`); return data; } }); `, errors: [ { messageId: 'missingDeps', data: { deps: 'id' }, suggestions: [ { messageId: 'fixTo', data: { result: '["entity", id]' }, output: normalizeIndent` const [id] = React.useState(1); useQuery({ queryKey: ["entity", id], queryFn: () => { const { data } = axios.get(\`.../\${id}\`); return data; } }); `, }, ], }, ], }, { name: 'should fail when dep does not exist while having a complex queryKey', code: normalizeIndent` const todoQueries = { key: (a, b, c, d, e) => ({ queryKey: ["entity", a, [b], { c }, 1, true], queryFn: () => api.getEntity(a, b, c, d, e) }) } `, errors: [ { messageId: 'missingDeps', data: { deps: 'd, e' }, suggestions: [ { messageId: 'fixTo', data: { result: '["entity", a, [b], { c }, 1, true, d, e]' }, output: normalizeIndent` const todoQueries = { key: (a, b, c, d, e) => ({ queryKey: ["entity", a, [b], { c }, 1, true, d, e], queryFn: () => api.getEntity(a, b, c, d, e) }) } `, }, ], }, ], }, { name: 'should fail when dep does not exist while having a complex queryKey #2', code: normalizeIndent` const todoQueries = { key: (dep1, dep2, dep3, dep4, dep5, dep6, dep7, dep8) => ({ queryKey: ['foo', {dep1, dep2: dep2, bar: dep3, baz: [dep4, dep5]}, [dep6, dep7]], queryFn: () => api.getEntity(dep1, dep2, dep3, dep4, dep5, dep6, dep7, dep8), }), }; `, errors: [ { messageId: 'missingDeps', data: { deps: 'dep8' }, suggestions: [ { messageId: 'fixTo', data: { result: "['foo', {dep1, dep2: dep2, bar: dep3, baz: [dep4, dep5]}, [dep6, dep7], dep8]", }, output: normalizeIndent` const todoQueries = { key: (dep1, dep2, dep3, dep4, dep5, dep6, dep7, dep8) => ({ queryKey: ['foo', {dep1, dep2: dep2, bar: dep3, baz: [dep4, dep5]}, [dep6, dep7], dep8], queryFn: () => api.getEntity(dep1, dep2, dep3, dep4, dep5, dep6, dep7, dep8), }), }; `, }, ], }, ], }, { name: 'should fail when two deps that depend on each other are missing', code: normalizeIndent` function Component({ map, key }) { useQuery({ queryKey: ["key"], queryFn: () => api.get(map[key]) }); } `, errors: [ { messageId: 'missingDeps', data: { deps: 'map[key]' }, suggestions: [ { messageId: 'fixTo', data: { result: '["key", map[key]]', }, output: normalizeIndent` function Component({ map, key }) { useQuery({ queryKey: ["key", map[key]], queryFn: () => api.get(map[key]) }); } `, }, ], }, ], }, { name: 'should fail when a queryKey is a reference of an array expression with a missing dep', code: normalizeIndent` const x = 5; const queryKey = ['foo'] useQuery({ queryKey, queryFn: () => x }) `, errors: [ { messageId: 'missingDeps', data: { deps: 'x' }, suggestions: [ { messageId: 'fixTo', data: { result: "['foo', x]", }, output: normalizeIndent` const x = 5; const queryKey = ['foo', x] useQuery({ queryKey, queryFn: () => x }) `, }, ], }, ], }, { name: 'should fail when a queryKey is a reference of an array expression with a missing dep', code: normalizeIndent` const x = 5; const queryKey = ['foo'] useQuery({ queryKey, queryFn: () => x }) `, errors: [ { messageId: 'missingDeps', data: { deps: 'x' }, suggestions: [ { messageId: 'fixTo', data: { result: "['foo', x]", }, output: normalizeIndent` const x = 5; const queryKey = ['foo', x] useQuery({ queryKey, queryFn: () => x }) `, }, ], }, ], }, { name: 'should fail when queryKey is a queryKeyFactory while having missing dep', code: normalizeIndent` const fooQueryKeyFactory = { foo: () => ['foo'] as const } const useFoo = (num: number) => useQuery({ queryKey: fooQueryKeyFactory.foo(), queryFn: () => Promise.resolve(num), }) `, errors: [ { messageId: 'missingDeps', data: { deps: 'num' }, }, ], }, { name: 'should fail if queryFn is using multiple object props when only one of them is in the queryKey', code: normalizeIndent` const state = { foo: 'foo', bar: 'bar' } useQuery({ queryKey: ['state', state.foo], queryFn: () => Promise.resolve({ foo: state.foo, bar: state.bar }) }) `, errors: [ { messageId: 'missingDeps', data: { deps: 'state.bar' }, }, ], }, ], })
3,820
0
petrpan-code/TanStack/query/packages/eslint-plugin-query/src/rules
petrpan-code/TanStack/query/packages/eslint-plugin-query/src/rules/no-rest-desctructuring/no-rest-destructuring.test.ts
import { ESLintUtils } from '@typescript-eslint/utils' import { normalizeIndent } from '../../utils/test-utils' import { rule } from './no-rest-destructuring.rule' const ruleTester = new ESLintUtils.RuleTester({ parser: '@typescript-eslint/parser', settings: {}, }) ruleTester.run('no-rest-desctructuring', rule, { valid: [ { name: 'useQuery is not captured', code: normalizeIndent` import { useQuery } from '@tanstack/react-query' function Component() { useQuery() return } `, }, { name: 'useQuery is not destructured', code: normalizeIndent` import { useQuery } from '@tanstack/react-query' function Component() { const query = useQuery() return } `, }, { name: 'useQuery is destructured without rest', code: normalizeIndent` import { useQuery } from '@tanstack/react-query' function Component() { const { data, isLoading, isError } = useQuery() return } `, }, { name: 'useInfiniteQuery is not captured', code: normalizeIndent` import { useInfiniteQuery } from '@tanstack/react-query' function Component() { useInfiniteQuery() return } `, }, { name: 'useInfiniteQuery is not destructured', code: normalizeIndent` import { useInfiniteQuery } from '@tanstack/react-query' function Component() { const query = useInfiniteQuery() return } `, }, { name: 'useInfiniteQuery is destructured without rest', code: normalizeIndent` import { useInfiniteQuery } from '@tanstack/react-query' function Component() { const { data, isLoading, isError } = useInfiniteQuery() return } `, }, { name: 'useQueries is not captured', code: normalizeIndent` import { useQueries } from '@tanstack/react-query' function Component() { useQueries([]) return } `, }, { name: 'useQueries is not destructured', code: normalizeIndent` import { useQueries } from '@tanstack/react-query' function Component() { const queries = useQueries([]) return } `, }, { name: 'useQueries array has no rest destructured element', code: normalizeIndent` import { useQueries } from '@tanstack/react-query' function Component() { const [query1, { data, isLoading },, ...others] = useQueries([ { queryKey: ['key1'], queryFn: () => {} }, { queryKey: ['key2'], queryFn: () => {} }, { queryKey: ['key3'], queryFn: () => {} }, { queryKey: ['key4'], queryFn: () => {} }, { queryKey: ['key5'], queryFn: () => {} }, ]) return } `, }, { name: 'useQuery is destructured with rest but not from tanstack query', code: normalizeIndent` import { useQuery } from 'other-package' function Component() { const { data, ...rest } = useQuery() return } `, }, { name: 'useInfiniteQuery is destructured with rest but not from tanstack query', code: normalizeIndent` import { useInfiniteQuery } from 'other-package' function Component() { const { data, ...rest } = useInfiniteQuery() return } `, }, { name: 'useQueries array has rest destructured element but not from tanstack query', code: normalizeIndent` import { useQueries } from 'other-package' function Component() { const [query1, { data, ...rest }] = useQueries([ { queryKey: ['key1'], queryFn: () => {} }, { queryKey: ['key2'], queryFn: () => {} }, ]) return } `, }, ], invalid: [ { name: 'useQuery is destructured with rest', code: normalizeIndent` import { useQuery } from '@tanstack/react-query' function Component() { const { data, ...rest } = useQuery() return } `, errors: [{ messageId: 'objectRestDestructure' }], }, { name: 'useInfiniteQuery is destructured with rest', code: normalizeIndent` import { useInfiniteQuery } from '@tanstack/react-query' function Component() { const { data, ...rest } = useInfiniteQuery() return } `, errors: [{ messageId: 'objectRestDestructure' }], }, { name: 'useQueries array has rest destructured element', code: normalizeIndent` import { useQueries } from '@tanstack/react-query' function Component() { const [query1, { data, ...rest }] = useQueries([ { queryKey: ['key1'], queryFn: () => {} }, { queryKey: ['key2'], queryFn: () => {} }, ]) return } `, errors: [{ messageId: 'objectRestDestructure' }], }, ], })
3,823
0
petrpan-code/TanStack/query/packages/eslint-plugin-query/src/rules
petrpan-code/TanStack/query/packages/eslint-plugin-query/src/rules/stable-query-client/stable-query-client.test.ts
import { ESLintUtils } from '@typescript-eslint/utils' import { normalizeIndent } from '../../utils/test-utils' import { rule } from './stable-query-client.rule' const ruleTester = new ESLintUtils.RuleTester({ parser: '@typescript-eslint/parser', settings: {}, }) ruleTester.run('stable-query-client', rule, { valid: [ { name: 'QueryClient is stable when wrapped in React.useState', code: normalizeIndent` import { QueryClient } from "@tanstack/react-query"; function Component() { const [queryClient] = React.useState(() => new QueryClient()); return; } `, }, { name: 'QueryClient is stable when wrapped in useState', code: normalizeIndent` import { QueryClient } from "@tanstack/react-query"; function Component() { const [queryClient] = useState(() => new QueryClient()); return; } `, }, { name: 'QueryClient is stable when wrapped in React.useMemo', code: normalizeIndent` import { QueryClient } from "@tanstack/react-query"; function Component() { const [queryClient] = React.useMemo(() => new QueryClient(), []); return; } `, }, { name: 'QueryClient is stable when wrapped in useAnything', code: normalizeIndent` import { QueryClient } from "@tanstack/react-query"; function Component() { const [queryClient] = useAnything(() => new QueryClient()); return; } `, }, { name: 'QueryClient is imported from a non-tanstack package', code: normalizeIndent` import { QueryClient } from "other-library"; function Component() { const queryClient = new QueryClient(); return; } `, }, { name: 'QueryClient is not imported from @tanstack/react-query', code: normalizeIndent` import { QueryClient } from "@tanstack/solid-query"; function Component() { const queryClient = new QueryClient(); return; } `, }, { name: 'QueryClient is invoked outside of a function', code: normalizeIndent` import { QueryClient } from "@tanstack/solid-query"; const queryClient = new QueryClient(); function Component() { return; } `, }, { name: 'QueryClient is invoked in a non-component function', code: normalizeIndent` import { QueryClient } from "@tanstack/solid-query"; function someFn() { const queryClient = new QueryClient(); return; } `, }, { name: 'QueryClient is invoked in an async (react server) component', code: normalizeIndent` import { QueryClient } from "@tanstack/solid-query"; async function AsyncComponent() { const queryClient = new QueryClient(); return; } `, }, ], invalid: [ { name: 'QueryClient is not stable when it is not wrapped in React.useState in component', code: normalizeIndent` import { QueryClient } from "@tanstack/react-query"; function Component() { const queryClient = new QueryClient(); return; } `, output: normalizeIndent` import { QueryClient } from "@tanstack/react-query"; function Component() { const [queryClient] = React.useState(() => new QueryClient()); return; } `, errors: [{ messageId: 'unstable' }], }, { name: 'QueryClient is not stable when it is not wrapped in React.useState in custom hook', code: normalizeIndent` import { QueryClient } from "@tanstack/react-query"; function useHook() { const queryClient = new QueryClient(); return; } `, output: normalizeIndent` import { QueryClient } from "@tanstack/react-query"; function useHook() { const [queryClient] = React.useState(() => new QueryClient()); return; } `, errors: [{ messageId: 'unstable' }], }, { name: 'preserve QueryClient options', code: normalizeIndent` import { QueryClient } from "@tanstack/react-query"; function Component() { const queryClient = new QueryClient({ defaultOptions: { /* */ } }); return; } `, output: normalizeIndent` import { QueryClient } from "@tanstack/react-query"; function Component() { const [queryClient] = React.useState(() => new QueryClient({ defaultOptions: { /* */ } })); return; } `, errors: [{ messageId: 'unstable' }], }, { name: 'preserve QueryClient variable declarator name', code: normalizeIndent` import { QueryClient } from "@tanstack/react-query"; function Component() { const customName = new QueryClient(); return; } `, output: normalizeIndent` import { QueryClient } from "@tanstack/react-query"; function Component() { const [customName] = React.useState(() => new QueryClient()); return; } `, errors: [{ messageId: 'unstable' }], }, ], })
3,837
0
petrpan-code/TanStack/query/packages/query-async-storage-persister/src
petrpan-code/TanStack/query/packages/query-async-storage-persister/src/__tests__/asyncThrottle.test.ts
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { asyncThrottle } from '../asyncThrottle' import { sleep as delay } from './utils' describe('asyncThrottle', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) test('basic', async () => { const interval = 10 const execTimeStamps: Array<number> = [] const mockFunc = vi.fn( async (id: number, complete?: (value?: unknown) => void) => { await delay(1) execTimeStamps.push(Date.now()) if (complete) { complete(id) } }, ) const testFunc = asyncThrottle(mockFunc, { interval }) testFunc(1) await vi.advanceTimersByTimeAsync(1) testFunc(2) await vi.advanceTimersByTimeAsync(1) new Promise((resolve) => testFunc(3, resolve)) await vi.advanceTimersToNextTimerAsync() await vi.advanceTimersByTimeAsync(interval) expect(mockFunc).toBeCalledTimes(2) expect(mockFunc.mock.calls[1]?.[0]).toBe(3) expect(execTimeStamps.length).toBe(2) expect(execTimeStamps[1]! - execTimeStamps[0]!).toBeGreaterThanOrEqual( interval, ) }) test('Bug #3331 case 1: Special timing', async () => { const interval = 1000 const execTimeStamps: Array<number> = [] const mockFunc = vi.fn( async (id: number, complete?: (value?: unknown) => void) => { await delay(30) execTimeStamps.push(Date.now()) if (complete) { complete(id) } }, ) const testFunc = asyncThrottle(mockFunc, { interval }) testFunc(1) testFunc(2) await vi.advanceTimersByTimeAsync(35) testFunc(3) await vi.advanceTimersByTimeAsync(35) new Promise((resolve) => testFunc(4, resolve)) await vi.advanceTimersToNextTimerAsync() await vi.advanceTimersByTimeAsync(interval) expect(mockFunc).toBeCalledTimes(2) expect(mockFunc.mock.calls[1]?.[0]).toBe(4) expect(execTimeStamps.length).toBe(2) expect(execTimeStamps[1]! - execTimeStamps[0]!).toBeGreaterThanOrEqual( interval, ) }) test('Bug #3331 case 2: "func" execution time is greater than the interval.', async () => { const interval = 1000 const execTimeStamps: Array<number> = [] const mockFunc = vi.fn( async (id: number, complete?: (value?: unknown) => void) => { await delay(interval + 10) execTimeStamps.push(Date.now()) if (complete) { complete(id) } }, ) const testFunc = asyncThrottle(mockFunc, { interval }) testFunc(1) testFunc(2) new Promise((resolve) => testFunc(3, resolve)) await vi.advanceTimersToNextTimerAsync() await vi.advanceTimersByTimeAsync(interval + 10) await vi.advanceTimersByTimeAsync(interval + 10) expect(mockFunc).toBeCalledTimes(2) expect(mockFunc.mock.calls[1]?.[0]).toBe(3) expect(execTimeStamps.length).toBe(2) expect(execTimeStamps[1]! - execTimeStamps[0]!).toBeGreaterThanOrEqual( interval, ) }) test('"func" throw error not break next invoke', async () => { const interval = 10 const mockFunc = vi.fn( async (id: number, complete?: (value?: unknown) => void) => { if (id === 1) throw new Error('error') await delay(1) if (complete) { complete(id) } }, ) const testFunc = asyncThrottle(mockFunc, { interval }) testFunc(1) await vi.advanceTimersByTimeAsync(1) new Promise((resolve) => testFunc(2, resolve)) await vi.advanceTimersByTimeAsync(interval) expect(mockFunc).toBeCalledTimes(2) expect(mockFunc.mock.calls[1]?.[0]).toBe(2) }) test('"onError" should be called when "func" throw error', () => { const err = new Error('error') const handleError = (e: unknown) => { expect(e).toBe(err) } const testFunc = asyncThrottle( () => { throw err }, { onError: handleError }, ) testFunc() }) test('should throw error when "func" is not a function', () => { expect(() => asyncThrottle(1 as any)).toThrowError() }) })
3,869
0
petrpan-code/TanStack/query/packages/query-core/src
petrpan-code/TanStack/query/packages/query-core/src/tests/focusManager.test.tsx
import { beforeEach, describe, expect, it, test, vi } from 'vitest' import { sleep } from '../utils' import { FocusManager } from '../focusManager' import { setIsServer } from './utils' describe('focusManager', () => { let focusManager: FocusManager beforeEach(() => { vi.resetModules() focusManager = new FocusManager() }) it('should call previous remove handler when replacing an event listener', () => { const remove1Spy = vi.fn() const remove2Spy = vi.fn() focusManager.setEventListener(() => remove1Spy) focusManager.setEventListener(() => remove2Spy) expect(remove1Spy).toHaveBeenCalledTimes(1) expect(remove2Spy).not.toHaveBeenCalled() }) it('should use focused boolean arg', async () => { let count = 0 const setup = (setFocused: (focused?: boolean) => void) => { setTimeout(() => { count++ setFocused(true) }, 20) return () => void 0 } focusManager.setEventListener(setup) await sleep(30) expect(count).toEqual(1) expect(focusManager.isFocused()).toBeTruthy() }) it('should return true for isFocused if document is undefined', async () => { const { document } = globalThis // @ts-expect-error delete globalThis.document focusManager.setFocused() expect(focusManager.isFocused()).toBeTruthy() globalThis.document = document }) test('cleanup (removeEventListener) should not be called if window is not defined', async () => { const restoreIsServer = setIsServer(true) const removeEventListenerSpy = vi.spyOn(globalThis, 'removeEventListener') const unsubscribe = focusManager.subscribe(() => undefined) unsubscribe() expect(removeEventListenerSpy).not.toHaveBeenCalled() restoreIsServer() }) test('cleanup (removeEventListener) should not be called if window.addEventListener is not defined', async () => { const { addEventListener } = globalThis.window // @ts-expect-error globalThis.window.addEventListener = undefined const removeEventListenerSpy = vi.spyOn(globalThis, 'removeEventListener') const unsubscribe = focusManager.subscribe(() => undefined) unsubscribe() expect(removeEventListenerSpy).not.toHaveBeenCalled() globalThis.window.addEventListener = addEventListener }) it('should replace default window listener when a new event listener is set', async () => { const unsubscribeSpy = vi.fn().mockImplementation(() => undefined) const handlerSpy = vi.fn().mockImplementation(() => unsubscribeSpy) focusManager.setEventListener(() => handlerSpy()) const unsubscribe = focusManager.subscribe(() => undefined) // Should call the custom event once expect(handlerSpy).toHaveBeenCalledTimes(1) unsubscribe() // Should unsubscribe our event event expect(unsubscribeSpy).toHaveBeenCalledTimes(1) handlerSpy.mockRestore() unsubscribeSpy.mockRestore() }) test('should call removeEventListener when last listener unsubscribes', () => { const addEventListenerSpy = vi.spyOn(globalThis.window, 'addEventListener') const removeEventListenerSpy = vi.spyOn( globalThis.window, 'removeEventListener', ) const unsubscribe1 = focusManager.subscribe(() => undefined) const unsubscribe2 = focusManager.subscribe(() => undefined) expect(addEventListenerSpy).toHaveBeenCalledTimes(1) // visibilitychange event unsubscribe1() expect(removeEventListenerSpy).toHaveBeenCalledTimes(0) unsubscribe2() expect(removeEventListenerSpy).toHaveBeenCalledTimes(1) // visibilitychange event }) test('should keep setup function even if last listener unsubscribes', () => { const setupSpy = vi.fn().mockImplementation(() => () => undefined) focusManager.setEventListener(setupSpy) const unsubscribe1 = focusManager.subscribe(() => undefined) expect(setupSpy).toHaveBeenCalledTimes(1) unsubscribe1() const unsubscribe2 = focusManager.subscribe(() => undefined) expect(setupSpy).toHaveBeenCalledTimes(2) unsubscribe2() }) test('should call listeners when setFocused is called', () => { const listener = vi.fn() focusManager.subscribe(listener) focusManager.setFocused(true) focusManager.setFocused(true) expect(listener).toHaveBeenCalledTimes(1) focusManager.setFocused(false) focusManager.setFocused(false) expect(listener).toHaveBeenCalledTimes(2) focusManager.setFocused(undefined) focusManager.setFocused(undefined) expect(listener).toHaveBeenCalledTimes(3) }) })
3,870
0
petrpan-code/TanStack/query/packages/query-core/src
petrpan-code/TanStack/query/packages/query-core/src/tests/hydration.test.tsx
import { describe, expect, test, vi } from 'vitest' import { QueryCache } from '../queryCache' import { dehydrate, hydrate } from '../hydration' import { MutationCache } from '../mutationCache' import { createQueryClient, executeMutation, mockOnlineManagerIsOnline, sleep, } from './utils' async function fetchData<TData>(value: TData, ms?: number): Promise<TData> { await sleep(ms || 0) return value } describe('dehydration and rehydration', () => { test('should work with serializeable values', async () => { const queryCache = new QueryCache() const queryClient = createQueryClient({ queryCache }) await queryClient.prefetchQuery({ queryKey: ['string'], queryFn: () => fetchData('string'), }) await queryClient.prefetchQuery({ queryKey: ['number'], queryFn: () => fetchData(1), }) await queryClient.prefetchQuery({ queryKey: ['boolean'], queryFn: () => fetchData(true), }) await queryClient.prefetchQuery({ queryKey: ['null'], queryFn: () => fetchData(null), }) await queryClient.prefetchQuery({ queryKey: ['array'], queryFn: () => fetchData(['string', 0]), }) await queryClient.prefetchQuery({ queryKey: ['nested'], queryFn: () => fetchData({ key: [{ nestedKey: 1 }] }), }) const dehydrated = dehydrate(queryClient) const stringified = JSON.stringify(dehydrated) // --- const parsed = JSON.parse(stringified) const hydrationCache = new QueryCache() const hydrationClient = createQueryClient({ queryCache: hydrationCache, }) hydrate(hydrationClient, parsed) expect(hydrationCache.find({ queryKey: ['string'] })?.state.data).toBe( 'string', ) expect(hydrationCache.find({ queryKey: ['number'] })?.state.data).toBe(1) expect(hydrationCache.find({ queryKey: ['boolean'] })?.state.data).toBe( true, ) expect(hydrationCache.find({ queryKey: ['null'] })?.state.data).toBe(null) expect(hydrationCache.find({ queryKey: ['array'] })?.state.data).toEqual([ 'string', 0, ]) expect(hydrationCache.find({ queryKey: ['nested'] })?.state.data).toEqual({ key: [{ nestedKey: 1 }], }) const fetchDataAfterHydration = vi.fn<Array<unknown>, unknown>() await hydrationClient.prefetchQuery({ queryKey: ['string'], queryFn: fetchDataAfterHydration, staleTime: 1000, }) await hydrationClient.prefetchQuery({ queryKey: ['number'], queryFn: fetchDataAfterHydration, staleTime: 1000, }) await hydrationClient.prefetchQuery({ queryKey: ['boolean'], queryFn: fetchDataAfterHydration, staleTime: 1000, }) await hydrationClient.prefetchQuery({ queryKey: ['null'], queryFn: fetchDataAfterHydration, staleTime: 1000, }) await hydrationClient.prefetchQuery({ queryKey: ['array'], queryFn: fetchDataAfterHydration, staleTime: 1000, }) await hydrationClient.prefetchQuery({ queryKey: ['nested'], queryFn: fetchDataAfterHydration, staleTime: 1000, }) expect(fetchDataAfterHydration).toHaveBeenCalledTimes(0) queryClient.clear() hydrationClient.clear() }) test('should not dehydrate queries if dehydrateQueries is set to false', async () => { const queryCache = new QueryCache() const queryClient = createQueryClient({ queryCache }) await queryClient.prefetchQuery({ queryKey: ['string'], queryFn: () => fetchData('string'), }) const dehydrated = dehydrate(queryClient, { shouldDehydrateQuery: () => false, }) expect(dehydrated.queries.length).toBe(0) queryClient.clear() }) test('should use the garbage collection time from the client', async () => { const queryCache = new QueryCache() const queryClient = createQueryClient({ queryCache }) await queryClient.prefetchQuery({ queryKey: ['string'], queryFn: () => fetchData('string'), gcTime: 50, }) const dehydrated = dehydrate(queryClient) const stringified = JSON.stringify(dehydrated) await sleep(20) // --- const parsed = JSON.parse(stringified) const hydrationCache = new QueryCache() const hydrationClient = createQueryClient({ queryCache: hydrationCache }) hydrate(hydrationClient, parsed) expect(hydrationCache.find({ queryKey: ['string'] })?.state.data).toBe( 'string', ) await sleep(100) expect(hydrationCache.find({ queryKey: ['string'] })).toBeTruthy() queryClient.clear() hydrationClient.clear() }) test('should be able to provide default options for the hydrated queries', async () => { const queryCache = new QueryCache() const queryClient = createQueryClient({ queryCache }) await queryClient.prefetchQuery({ queryKey: ['string'], queryFn: () => fetchData('string'), }) const dehydrated = dehydrate(queryClient) const stringified = JSON.stringify(dehydrated) const parsed = JSON.parse(stringified) const hydrationCache = new QueryCache() const hydrationClient = createQueryClient({ queryCache: hydrationCache }) hydrate(hydrationClient, parsed, { defaultOptions: { queries: { retry: 10 } }, }) expect(hydrationCache.find({ queryKey: ['string'] })?.options.retry).toBe( 10, ) queryClient.clear() hydrationClient.clear() }) test('should work with complex keys', async () => { const queryCache = new QueryCache() const queryClient = createQueryClient({ queryCache }) await queryClient.prefetchQuery({ queryKey: ['string', { key: ['string'], key2: 0 }], queryFn: () => fetchData('string'), }) const dehydrated = dehydrate(queryClient) const stringified = JSON.stringify(dehydrated) // --- const parsed = JSON.parse(stringified) const hydrationCache = new QueryCache() const hydrationClient = createQueryClient({ queryCache: hydrationCache }) hydrate(hydrationClient, parsed) expect( hydrationCache.find({ queryKey: ['string', { key: ['string'], key2: 0 }], })?.state.data, ).toBe('string') const fetchDataAfterHydration = vi.fn<Array<unknown>, unknown>() await hydrationClient.prefetchQuery({ queryKey: ['string', { key: ['string'], key2: 0 }], queryFn: fetchDataAfterHydration, staleTime: 100, }) expect(fetchDataAfterHydration).toHaveBeenCalledTimes(0) queryClient.clear() hydrationClient.clear() }) test('should only hydrate successful queries by default', async () => { const consoleMock = vi.spyOn(console, 'error') consoleMock.mockImplementation(() => undefined) const queryCache = new QueryCache() const queryClient = createQueryClient({ queryCache }) await queryClient.prefetchQuery({ queryKey: ['success'], queryFn: () => fetchData('success'), }) queryClient.prefetchQuery({ queryKey: ['loading'], queryFn: () => fetchData('loading', 10000), }) await queryClient.prefetchQuery({ queryKey: ['error'], queryFn: () => { throw new Error() }, }) const dehydrated = dehydrate(queryClient) const stringified = JSON.stringify(dehydrated) // --- const parsed = JSON.parse(stringified) const hydrationCache = new QueryCache() const hydrationClient = createQueryClient({ queryCache: hydrationCache }) hydrate(hydrationClient, parsed) expect(hydrationCache.find({ queryKey: ['success'] })).toBeTruthy() expect(hydrationCache.find({ queryKey: ['loading'] })).toBeFalsy() expect(hydrationCache.find({ queryKey: ['error'] })).toBeFalsy() queryClient.clear() hydrationClient.clear() consoleMock.mockRestore() }) test('should filter queries via dehydrateQuery', async () => { const queryCache = new QueryCache() const queryClient = createQueryClient({ queryCache }) await queryClient.prefetchQuery({ queryKey: ['string'], queryFn: () => fetchData('string'), }) await queryClient.prefetchQuery({ queryKey: ['number'], queryFn: () => fetchData(1), }) const dehydrated = dehydrate(queryClient, { shouldDehydrateQuery: (query) => query.queryKey[0] !== 'string', }) // This is testing implementation details that can change and are not // part of the public API, but is important for keeping the payload small const dehydratedQuery = dehydrated.queries.find( (query) => query.queryKey[0] === 'string', ) expect(dehydratedQuery).toBeUndefined() const stringified = JSON.stringify(dehydrated) // --- const parsed = JSON.parse(stringified) const hydrationCache = new QueryCache() const hydrationClient = createQueryClient({ queryCache: hydrationCache }) hydrate(hydrationClient, parsed) expect(hydrationCache.find({ queryKey: ['string'] })).toBeUndefined() expect(hydrationCache.find({ queryKey: ['number'] })?.state.data).toBe(1) queryClient.clear() hydrationClient.clear() }) test('should not overwrite query in cache if hydrated query is older', async () => { const queryCache = new QueryCache() const queryClient = createQueryClient({ queryCache }) await queryClient.prefetchQuery({ queryKey: ['string'], queryFn: () => fetchData('string-older', 5), }) const dehydrated = dehydrate(queryClient) const stringified = JSON.stringify(dehydrated) // --- const parsed = JSON.parse(stringified) const hydrationCache = new QueryCache() const hydrationClient = createQueryClient({ queryCache: hydrationCache }) await hydrationClient.prefetchQuery({ queryKey: ['string'], queryFn: () => fetchData('string-newer', 5), }) hydrate(hydrationClient, parsed) expect(hydrationCache.find({ queryKey: ['string'] })?.state.data).toBe( 'string-newer', ) queryClient.clear() hydrationClient.clear() }) test('should overwrite query in cache if hydrated query is newer', async () => { const hydrationCache = new QueryCache() const hydrationClient = createQueryClient({ queryCache: hydrationCache }) await hydrationClient.prefetchQuery({ queryKey: ['string'], queryFn: () => fetchData('string-older', 5), }) // --- const queryCache = new QueryCache() const queryClient = createQueryClient({ queryCache }) await queryClient.prefetchQuery({ queryKey: ['string'], queryFn: () => fetchData('string-newer', 5), }) const dehydrated = dehydrate(queryClient) const stringified = JSON.stringify(dehydrated) // --- const parsed = JSON.parse(stringified) hydrate(hydrationClient, parsed) expect(hydrationCache.find({ queryKey: ['string'] })?.state.data).toBe( 'string-newer', ) queryClient.clear() hydrationClient.clear() }) test('should be able to dehydrate mutations and continue on hydration', async () => { const consoleMock = vi.spyOn(console, 'error') consoleMock.mockImplementation(() => undefined) const onlineMock = mockOnlineManagerIsOnline(false) const serverAddTodo = vi .fn() .mockImplementation(() => Promise.reject(new Error('offline'))) const serverOnMutate = vi.fn().mockImplementation((variables) => { const optimisticTodo = { id: 1, text: variables.text } return { optimisticTodo } }) const serverOnSuccess = vi.fn() const serverClient = createQueryClient() serverClient.setMutationDefaults(['addTodo'], { mutationFn: serverAddTodo, onMutate: serverOnMutate, onSuccess: serverOnSuccess, retry: 3, retryDelay: 10, }) executeMutation( serverClient, { mutationKey: ['addTodo'], }, { text: 'text' }, ).catch(() => undefined) await sleep(50) const dehydrated = dehydrate(serverClient) const stringified = JSON.stringify(dehydrated) serverClient.clear() // --- onlineMock.mockReturnValue(true) const parsed = JSON.parse(stringified) const client = createQueryClient() const clientAddTodo = vi.fn().mockImplementation((variables) => { return { id: 2, text: variables.text } }) const clientOnMutate = vi.fn().mockImplementation((variables) => { const optimisticTodo = { id: 1, text: variables.text } return { optimisticTodo } }) const clientOnSuccess = vi.fn() client.setMutationDefaults(['addTodo'], { mutationFn: clientAddTodo, onMutate: clientOnMutate, onSuccess: clientOnSuccess, retry: 3, retryDelay: 10, }) hydrate(client, parsed) await client.resumePausedMutations() expect(clientAddTodo).toHaveBeenCalledTimes(1) expect(clientOnMutate).not.toHaveBeenCalled() expect(clientOnSuccess).toHaveBeenCalledTimes(1) expect(clientOnSuccess).toHaveBeenCalledWith( { id: 2, text: 'text' }, { text: 'text' }, { optimisticTodo: { id: 1, text: 'text' } }, ) client.clear() consoleMock.mockRestore() onlineMock.mockRestore() }) test('should not dehydrate mutations if dehydrateMutations is set to false', async () => { const consoleMock = vi.spyOn(console, 'error') consoleMock.mockImplementation(() => undefined) const serverAddTodo = vi .fn() .mockImplementation(() => Promise.reject(new Error('offline'))) const queryClient = createQueryClient() queryClient.setMutationDefaults(['addTodo'], { mutationFn: serverAddTodo, retry: false, }) executeMutation( queryClient, { mutationKey: ['addTodo'], }, { text: 'text' }, ).catch(() => undefined) await sleep(1) const dehydrated = dehydrate(queryClient, { shouldDehydrateMutation: () => false, }) expect(dehydrated.mutations.length).toBe(0) queryClient.clear() consoleMock.mockRestore() }) test('should not dehydrate mutation if mutation state is set to pause', async () => { const consoleMock = vi.spyOn(console, 'error') consoleMock.mockImplementation(() => undefined) const serverAddTodo = vi .fn() .mockImplementation(() => Promise.reject(new Error('offline'))) const queryClient = createQueryClient() queryClient.setMutationDefaults(['addTodo'], { mutationFn: serverAddTodo, retry: 1, retryDelay: 20, }) executeMutation( queryClient, { mutationKey: ['addTodo'], }, { text: 'text' }, ).catch(() => undefined) // Dehydrate mutation between retries await sleep(1) const dehydrated = dehydrate(queryClient) expect(dehydrated.mutations.length).toBe(0) await sleep(30) queryClient.clear() consoleMock.mockRestore() }) test('should not hydrate if the hydratedState is null or is not an object', async () => { const queryCache = new QueryCache() const queryClient = createQueryClient({ queryCache }) expect(() => hydrate(queryClient, null)).not.toThrow() expect(() => hydrate(queryClient, 'invalid')).not.toThrow() queryClient.clear() }) test('should support hydratedState with undefined queries and mutations', async () => { const queryCache = new QueryCache() const queryClient = createQueryClient({ queryCache }) expect(() => hydrate(queryClient, {})).not.toThrow() expect(() => hydrate(queryClient, {})).not.toThrow() queryClient.clear() }) test('should set the fetchStatus to idle when creating a query with dehydrate', async () => { const queryCache = new QueryCache() const queryClient = createQueryClient({ queryCache }) let isInitialFetch = true let resolvePromise: (value: unknown) => void = () => undefined const customFetchData = () => { const promise = new Promise((resolve) => { resolvePromise = resolve }) // Resolve the promise in initial fetch // because we are awaiting the query first time if (isInitialFetch) { resolvePromise('string') } isInitialFetch = false return promise } await queryClient.prefetchQuery({ queryKey: ['string'], queryFn: () => customFetchData(), }) queryClient.refetchQueries({ queryKey: ['string'] }) const dehydrated = dehydrate(queryClient) resolvePromise('string') expect( dehydrated.queries.find((q) => q.queryHash === '["string"]')?.state .fetchStatus, ).toBe('fetching') const stringified = JSON.stringify(dehydrated) // --- const parsed = JSON.parse(stringified) const hydrationCache = new QueryCache() const hydrationClient = createQueryClient({ queryCache: hydrationCache }) hydrate(hydrationClient, parsed) expect( hydrationCache.find({ queryKey: ['string'] })?.state.fetchStatus, ).toBe('idle') }) test('should dehydrate and hydrate meta for queries', async () => { const queryCache = new QueryCache() const queryClient = createQueryClient({ queryCache }) await queryClient.prefetchQuery({ queryKey: ['meta'], queryFn: () => Promise.resolve('meta'), meta: { some: 'meta', }, }) await queryClient.prefetchQuery({ queryKey: ['no-meta'], queryFn: () => Promise.resolve('no-meta'), }) const dehydrated = dehydrate(queryClient) expect( dehydrated.queries.find((q) => q.queryHash === '["meta"]')?.meta, ).toEqual({ some: 'meta', }) expect( dehydrated.queries.find((q) => q.queryHash === '["no-meta"]')?.meta, ).toEqual(undefined) expect( Object.keys( dehydrated.queries.find((q) => q.queryHash === '["no-meta"]')!, ), ).not.toEqual(expect.arrayContaining(['meta'])) const stringified = JSON.stringify(dehydrated) // --- const parsed = JSON.parse(stringified) const hydrationCache = new QueryCache() const hydrationClient = createQueryClient({ queryCache: hydrationCache, }) hydrate(hydrationClient, parsed) expect(hydrationCache.find({ queryKey: ['meta'] })?.meta).toEqual({ some: 'meta', }) expect(hydrationCache.find({ queryKey: ['no-meta'] })?.meta).toEqual( undefined, ) }) test('should dehydrate and hydrate meta for mutations', async () => { const mutationCache = new MutationCache() const queryClient = createQueryClient({ mutationCache }) await executeMutation( queryClient, { mutationKey: ['meta'], mutationFn: () => Promise.resolve('meta'), meta: { some: 'meta', }, }, undefined, ) await executeMutation( queryClient, { mutationKey: ['no-meta'], mutationFn: () => Promise.resolve('no-meta'), }, undefined, ) const dehydrated = dehydrate(queryClient, { shouldDehydrateMutation: () => true, }) expect(Object.keys(dehydrated.mutations[0]!)).toEqual( expect.arrayContaining(['meta']), ) expect(dehydrated.mutations[0]?.meta).toEqual({ some: 'meta', }) expect(Object.keys(dehydrated.mutations[1]!)).not.toEqual( expect.arrayContaining(['meta']), ) expect(dehydrated.mutations[1]?.meta).toEqual(undefined) const stringified = JSON.stringify(dehydrated) // --- const parsed = JSON.parse(stringified) const hydrationCache = new MutationCache() const hydrationClient = createQueryClient({ mutationCache: hydrationCache, }) hydrate(hydrationClient, parsed) expect(hydrationCache.find({ mutationKey: ['meta'] })?.meta).toEqual({ some: 'meta', }) expect(hydrationCache.find({ mutationKey: ['no-meta'] })?.meta).toEqual( undefined, ) }) test('should not change fetchStatus when updating a query with dehydrate', async () => { const queryClient = createQueryClient() const options = { queryKey: ['string'], queryFn: async () => { await sleep(10) return 'string' }, } as const await queryClient.prefetchQuery(options) const dehydrated = dehydrate(queryClient) expect( dehydrated.queries.find((q) => q.queryHash === '["string"]')?.state .fetchStatus, ).toBe('idle') const stringified = JSON.stringify(dehydrated) // --- const parsed = JSON.parse(stringified) const hydrationCache = new QueryCache() const hydrationClient = createQueryClient({ queryCache: hydrationCache }) const promise = hydrationClient.prefetchQuery(options) hydrate(hydrationClient, parsed) expect( hydrationCache.find({ queryKey: ['string'] })?.state.fetchStatus, ).toBe('fetching') await promise expect( hydrationCache.find({ queryKey: ['string'] })?.state.fetchStatus, ).toBe('idle') }) })
3,871
0
petrpan-code/TanStack/query/packages/query-core/src
petrpan-code/TanStack/query/packages/query-core/src/tests/infiniteQueryBehavior.test.tsx
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { waitFor } from '@testing-library/react' import { CancelledError, InfiniteQueryObserver } from '..' import { createQueryClient, queryKey, sleep } from './utils' import type { InfiniteQueryObserverResult, QueryCache, QueryClient } from '..' describe('InfiniteQueryBehavior', () => { let queryClient: QueryClient let queryCache: QueryCache beforeEach(() => { queryClient = createQueryClient() queryCache = queryClient.getQueryCache() queryClient.mount() }) afterEach(() => { queryClient.clear() }) test('InfiniteQueryBehavior should throw an error if the queryFn is not defined', async () => { const key = queryKey() const observer = new InfiniteQueryObserver(queryClient, { queryKey: key, retry: false, initialPageParam: 1, getNextPageParam: () => 2, }) let observerResult: | InfiniteQueryObserverResult<unknown, unknown> | undefined const unsubscribe = observer.subscribe((result) => { observerResult = result }) await waitFor(() => { const query = queryCache.find({ queryKey: key })! return expect(observerResult).toMatchObject({ isError: true, error: new Error(`Missing queryFn: '${query.queryHash}'`), }) }) unsubscribe() }) test('InfiniteQueryBehavior should apply the maxPages option to limit the number of pages', async () => { const key = queryKey() let abortSignal: AbortSignal | null = null const queryFnSpy = vi.fn().mockImplementation(({ pageParam, signal }) => { abortSignal = signal return pageParam }) const observer = new InfiniteQueryObserver<number>(queryClient, { queryKey: key, queryFn: queryFnSpy, getNextPageParam: (lastPage) => lastPage + 1, getPreviousPageParam: (firstPage) => firstPage - 1, maxPages: 2, initialPageParam: 1, }) let observerResult: | InfiniteQueryObserverResult<unknown, unknown> | undefined const unsubscribe = observer.subscribe((result) => { observerResult = result }) // Wait for the first page to be fetched await waitFor(() => expect(observerResult).toMatchObject({ isFetching: false, data: { pages: [1], pageParams: [1] }, }), ) expect(queryFnSpy).toHaveBeenNthCalledWith(1, { queryKey: key, pageParam: 1, meta: undefined, direction: 'forward', signal: abortSignal, }) queryFnSpy.mockClear() // Fetch the second page await observer.fetchNextPage() expect(queryFnSpy).toHaveBeenNthCalledWith(1, { queryKey: key, pageParam: 2, direction: 'forward', meta: undefined, signal: abortSignal, }) expect(observerResult).toMatchObject({ isFetching: false, data: { pages: [1, 2], pageParams: [1, 2] }, }) queryFnSpy.mockClear() // Fetch the page before the first page await observer.fetchPreviousPage() expect(queryFnSpy).toHaveBeenNthCalledWith(1, { queryKey: key, pageParam: 0, direction: 'backward', meta: undefined, signal: abortSignal, }) // Only first two pages should be in the data expect(observerResult).toMatchObject({ isFetching: false, data: { pages: [0, 1], pageParams: [0, 1] }, }) queryFnSpy.mockClear() // Fetch the page before await observer.fetchPreviousPage() expect(queryFnSpy).toHaveBeenNthCalledWith(1, { queryKey: key, pageParam: -1, meta: undefined, direction: 'backward', signal: abortSignal, }) expect(observerResult).toMatchObject({ isFetching: false, data: { pages: [-1, 0], pageParams: [-1, 0] }, }) queryFnSpy.mockClear() // Fetch the page after await observer.fetchNextPage() expect(queryFnSpy).toHaveBeenNthCalledWith(1, { queryKey: key, pageParam: 1, meta: undefined, direction: 'forward', signal: abortSignal, }) expect(observerResult).toMatchObject({ isFetching: false, data: { pages: [0, 1] }, }) queryFnSpy.mockClear() // Refetch the infinite query await observer.refetch() // Only 2 pages should be refetched expect(queryFnSpy).toHaveBeenCalledTimes(2) expect(queryFnSpy).toHaveBeenNthCalledWith(1, { queryKey: key, pageParam: 0, meta: undefined, direction: 'forward', signal: abortSignal, }) expect(queryFnSpy).toHaveBeenNthCalledWith(2, { queryKey: key, pageParam: 1, meta: undefined, direction: 'forward', signal: abortSignal, }) unsubscribe() }) test('InfiniteQueryBehavior should support query cancellation', async () => { const key = queryKey() let abortSignal: AbortSignal | null = null const queryFnSpy = vi.fn().mockImplementation(({ pageParam, signal }) => { abortSignal = signal sleep(10) return pageParam }) const observer = new InfiniteQueryObserver<number>(queryClient, { queryKey: key, queryFn: queryFnSpy, getNextPageParam: (lastPage) => lastPage + 1, getPreviousPageParam: (firstPage) => firstPage - 1, initialPageParam: 1, }) let observerResult: | InfiniteQueryObserverResult<unknown, unknown> | undefined const unsubscribe = observer.subscribe((result) => { observerResult = result }) const query = observer.getCurrentQuery() query.cancel() // Wait for the first page to be cancelled await waitFor(() => expect(observerResult).toMatchObject({ isFetching: false, isError: true, error: new CancelledError(), data: undefined, }), ) expect(queryFnSpy).toHaveBeenCalledTimes(1) expect(queryFnSpy).toHaveBeenNthCalledWith(1, { queryKey: key, pageParam: 1, meta: undefined, direction: 'forward', signal: abortSignal, }) unsubscribe() }) test('InfiniteQueryBehavior should not refetch pages if the query is cancelled', async () => { const key = queryKey() let abortSignal: AbortSignal | null = null let queryFnSpy = vi.fn().mockImplementation(({ pageParam, signal }) => { abortSignal = signal return pageParam }) const observer = new InfiniteQueryObserver<number>(queryClient, { queryKey: key, queryFn: queryFnSpy, getNextPageParam: (lastPage) => lastPage + 1, getPreviousPageParam: (firstPage) => firstPage - 1, initialPageParam: 1, }) let observerResult: | InfiniteQueryObserverResult<unknown, unknown> | undefined const unsubscribe = observer.subscribe((result) => { observerResult = result }) // Wait for the first page to be fetched await waitFor(() => expect(observerResult).toMatchObject({ isFetching: false, data: { pages: [1], pageParams: [1] }, }), ) queryFnSpy.mockClear() // Fetch the second page await observer.fetchNextPage() expect(observerResult).toMatchObject({ isFetching: false, data: { pages: [1, 2], pageParams: [1, 2] }, }) expect(queryFnSpy).toHaveBeenCalledTimes(1) expect(queryFnSpy).toHaveBeenNthCalledWith(1, { queryKey: key, pageParam: 2, meta: undefined, direction: 'forward', signal: abortSignal, }) queryFnSpy = vi.fn().mockImplementation(({ pageParam = 1, signal }) => { abortSignal = signal sleep(10) return pageParam }) // Refetch the query observer.refetch() expect(observerResult).toMatchObject({ isFetching: true, isError: false, }) // Cancel the query const query = observer.getCurrentQuery() query.cancel() expect(observerResult).toMatchObject({ isFetching: false, isError: true, error: new CancelledError(), data: { pages: [1, 2], pageParams: [1, 2] }, }) // Pages should not have been fetched expect(queryFnSpy).toHaveBeenCalledTimes(0) unsubscribe() }) })
3,872
0
petrpan-code/TanStack/query/packages/query-core/src
petrpan-code/TanStack/query/packages/query-core/src/tests/infiniteQueryObserver.test.tsx
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { InfiniteQueryObserver } from '..' import { createQueryClient, queryKey, sleep } from './utils' import type { QueryClient } from '..' describe('InfiniteQueryObserver', () => { let queryClient: QueryClient beforeEach(() => { queryClient = createQueryClient() queryClient.mount() }) afterEach(() => { queryClient.clear() }) test('InfiniteQueryObserver should be able to fetch an infinite query with selector', async () => { const key = queryKey() const observer = new InfiniteQueryObserver(queryClient, { queryKey: key, queryFn: () => 1, select: (data) => ({ pages: data.pages.map((x) => `${x}`), pageParams: data.pageParams, }), initialPageParam: 1, getNextPageParam: () => 2, }) let observerResult const unsubscribe = observer.subscribe((result) => { observerResult = result }) await sleep(1) unsubscribe() expect(observerResult).toMatchObject({ data: { pages: ['1'], pageParams: [1] }, }) }) test('InfiniteQueryObserver should pass the meta option to the queryFn', async () => { const meta = { it: 'works', } const key = queryKey() const queryFn = vi.fn(() => 1) const observer = new InfiniteQueryObserver(queryClient, { meta, queryKey: key, queryFn, select: (data) => ({ pages: data.pages.map((x) => `${x}`), pageParams: data.pageParams, }), initialPageParam: 1, getNextPageParam: () => 2, }) let observerResult const unsubscribe = observer.subscribe((result) => { observerResult = result }) await sleep(1) unsubscribe() expect(observerResult).toMatchObject({ data: { pages: ['1'], pageParams: [1] }, }) expect(queryFn).toBeCalledWith(expect.objectContaining({ meta })) }) test('getNextPagParam and getPreviousPageParam should receive current pageParams', async () => { const key = queryKey() let single: Array<string> = [] let all: Array<string> = [] const observer = new InfiniteQueryObserver(queryClient, { queryKey: key, queryFn: ({ pageParam }) => String(pageParam), initialPageParam: 1, getNextPageParam: (_, __, lastPageParam, allPageParams) => { single.push('next' + lastPageParam) all.push('next' + allPageParams.join(',')) return lastPageParam + 1 }, getPreviousPageParam: (_, __, firstPageParam, allPageParams) => { single.push('prev' + firstPageParam) all.push('prev' + allPageParams.join(',')) return firstPageParam - 1 }, }) await observer.fetchNextPage() await observer.fetchPreviousPage() expect(single).toEqual(['next1', 'prev1', 'prev1', 'next1', 'prev0']) expect(all).toEqual(['next1', 'prev1', 'prev1', 'next0,1', 'prev0,1']) single = [] all = [] await observer.refetch() expect(single).toEqual(['next0', 'next1', 'prev0']) expect(all).toEqual(['next0', 'next0,1', 'prev0,1']) }) test('should stop refetching if undefined is returned from getNextPageParam', async () => { const key = queryKey() let next: number | undefined = 2 const queryFn = vi.fn<any, any>(({ pageParam }) => String(pageParam)) const observer = new InfiniteQueryObserver(queryClient, { queryKey: key, queryFn, initialPageParam: 1, getNextPageParam: () => next, }) await observer.fetchNextPage() await observer.fetchNextPage() expect(observer.getCurrentResult().data?.pages).toEqual(['1', '2']) expect(queryFn).toBeCalledTimes(2) expect(observer.getCurrentResult().hasNextPage).toBe(true) next = undefined await observer.refetch() expect(observer.getCurrentResult().data?.pages).toEqual(['1']) expect(queryFn).toBeCalledTimes(3) expect(observer.getCurrentResult().hasNextPage).toBe(false) }) test('should stop refetching if null is returned from getNextPageParam', async () => { const key = queryKey() let next: number | null = 2 const queryFn = vi.fn<any, any>(({ pageParam }) => String(pageParam)) const observer = new InfiniteQueryObserver(queryClient, { queryKey: key, queryFn, initialPageParam: 1, getNextPageParam: () => next, }) await observer.fetchNextPage() await observer.fetchNextPage() expect(observer.getCurrentResult().data?.pages).toEqual(['1', '2']) expect(queryFn).toBeCalledTimes(2) expect(observer.getCurrentResult().hasNextPage).toBe(true) next = null await observer.refetch() expect(observer.getCurrentResult().data?.pages).toEqual(['1']) expect(queryFn).toBeCalledTimes(3) expect(observer.getCurrentResult().hasNextPage).toBe(false) }) })
3,873
0
petrpan-code/TanStack/query/packages/query-core/src
petrpan-code/TanStack/query/packages/query-core/src/tests/mutationCache.test.tsx
import { describe, expect, test, vi } from 'vitest' import { waitFor } from '@testing-library/react' import { MutationCache, MutationObserver } from '..' import { createQueryClient, executeMutation, queryKey, sleep } from './utils' describe('mutationCache', () => { describe('MutationCacheConfig error callbacks', () => { test('should call onError and onSettled when a mutation errors', async () => { const key = queryKey() const onError = vi.fn() const onSuccess = vi.fn() const onSettled = vi.fn() const testCache = new MutationCache({ onError, onSuccess, onSettled }) const testClient = createQueryClient({ mutationCache: testCache }) try { await executeMutation( testClient, { mutationKey: key, mutationFn: () => Promise.reject(new Error('error')), onMutate: () => 'context', }, 'vars', ) } catch {} const mutation = testCache.getAll()[0] expect(onError).toHaveBeenCalledTimes(1) expect(onError).toHaveBeenCalledWith( new Error('error'), 'vars', 'context', mutation, ) expect(onSuccess).not.toHaveBeenCalled() expect(onSettled).toHaveBeenCalledTimes(1) expect(onSettled).toHaveBeenCalledWith( undefined, new Error('error'), 'vars', 'context', mutation, ) }) test('should be awaited', async () => { const key = queryKey() const states: Array<number> = [] const onError = async () => { states.push(1) await sleep(1) states.push(2) } const onSettled = async () => { states.push(5) await sleep(1) states.push(6) } const testCache = new MutationCache({ onError, onSettled }) const testClient = createQueryClient({ mutationCache: testCache }) try { await executeMutation( testClient, { mutationKey: key, mutationFn: () => Promise.reject(new Error('error')), onError: async () => { states.push(3) await sleep(1) states.push(4) }, onSettled: async () => { states.push(7) await sleep(1) states.push(8) }, }, 'vars', ) } catch {} expect(states).toEqual([1, 2, 3, 4, 5, 6, 7, 8]) }) }) describe('MutationCacheConfig success callbacks', () => { test('should call onSuccess and onSettled when a mutation is successful', async () => { const key = queryKey() const onError = vi.fn() const onSuccess = vi.fn() const onSettled = vi.fn() const testCache = new MutationCache({ onError, onSuccess, onSettled }) const testClient = createQueryClient({ mutationCache: testCache }) try { await executeMutation( testClient, { mutationKey: key, mutationFn: () => Promise.resolve({ data: 5 }), onMutate: () => 'context', }, 'vars', ) } catch {} const mutation = testCache.getAll()[0] expect(onSuccess).toHaveBeenCalledTimes(1) expect(onSuccess).toHaveBeenCalledWith( { data: 5 }, 'vars', 'context', mutation, ) expect(onError).not.toHaveBeenCalled() expect(onSettled).toHaveBeenCalledTimes(1) expect(onSettled).toHaveBeenCalledWith( { data: 5 }, null, 'vars', 'context', mutation, ) }) test('should be awaited', async () => { const key = queryKey() const states: Array<number> = [] const onSuccess = async () => { states.push(1) await sleep(1) states.push(2) } const onSettled = async () => { states.push(5) await sleep(1) states.push(6) } const testCache = new MutationCache({ onSuccess, onSettled }) const testClient = createQueryClient({ mutationCache: testCache }) await executeMutation( testClient, { mutationKey: key, mutationFn: () => Promise.resolve({ data: 5 }), onSuccess: async () => { states.push(3) await sleep(1) states.push(4) }, onSettled: async () => { states.push(7) await sleep(1) states.push(8) }, }, 'vars', ) expect(states).toEqual([1, 2, 3, 4, 5, 6, 7, 8]) }) }) describe('MutationCacheConfig.onMutate', () => { test('should be called before a mutation executes', async () => { const key = queryKey() const onMutate = vi.fn() const testCache = new MutationCache({ onMutate }) const testClient = createQueryClient({ mutationCache: testCache }) try { await executeMutation( testClient, { mutationKey: key, mutationFn: () => Promise.resolve({ data: 5 }), onMutate: () => 'context', }, 'vars', ) } catch {} const mutation = testCache.getAll()[0] expect(onMutate).toHaveBeenCalledWith('vars', mutation) }) test('should be awaited', async () => { const key = queryKey() const states: Array<number> = [] const onMutate = async () => { states.push(1) await sleep(1) states.push(2) } const testCache = new MutationCache({ onMutate }) const testClient = createQueryClient({ mutationCache: testCache }) await executeMutation( testClient, { mutationKey: key, mutationFn: () => Promise.resolve({ data: 5 }), onMutate: async () => { states.push(3) await sleep(1) states.push(4) }, }, 'vars', ) expect(states).toEqual([1, 2, 3, 4]) }) }) describe('find', () => { test('should filter correctly', async () => { const testCache = new MutationCache() const testClient = createQueryClient({ mutationCache: testCache }) const key = ['mutation', 'vars'] await executeMutation( testClient, { mutationKey: key, mutationFn: () => Promise.resolve(), }, 'vars', ) const [mutation] = testCache.getAll() expect(testCache.find({ mutationKey: key })).toEqual(mutation) expect( testCache.find({ mutationKey: ['mutation'], exact: false }), ).toEqual(mutation) expect(testCache.find({ mutationKey: ['unknown'] })).toEqual(undefined) expect( testCache.find({ predicate: (m) => m.options.mutationKey?.[0] === key[0], }), ).toEqual(mutation) }) }) describe('findAll', () => { test('should filter correctly', async () => { const testCache = new MutationCache() const testClient = createQueryClient({ mutationCache: testCache }) await executeMutation( testClient, { mutationKey: ['a', 1], mutationFn: () => Promise.resolve(), }, 1, ) await executeMutation( testClient, { mutationKey: ['a', 2], mutationFn: () => Promise.resolve(), }, 2, ) await executeMutation( testClient, { mutationKey: ['b'], mutationFn: () => Promise.resolve(), }, 3, ) const [mutation1, mutation2] = testCache.getAll() expect( testCache.findAll({ mutationKey: ['a'], exact: false }), ).toHaveLength(2) expect(testCache.find({ mutationKey: ['a', 1] })).toEqual(mutation1) expect( testCache.findAll({ predicate: (m) => m.options.mutationKey?.[1] === 2, }), ).toEqual([mutation2]) expect(testCache.findAll({ mutationKey: ['unknown'] })).toEqual([]) }) }) describe('garbage collection', () => { test('should remove unused mutations after gcTime has elapsed', async () => { const testCache = new MutationCache() const testClient = createQueryClient({ mutationCache: testCache }) const onSuccess = vi.fn() await executeMutation( testClient, { mutationKey: ['a', 1], gcTime: 10, mutationFn: () => Promise.resolve(), onSuccess, }, 1, ) expect(testCache.getAll()).toHaveLength(1) await sleep(10) await waitFor(() => { expect(testCache.getAll()).toHaveLength(0) }) expect(onSuccess).toHaveBeenCalledTimes(1) }) test('should not remove mutations if there are active observers', async () => { const queryClient = createQueryClient() const observer = new MutationObserver(queryClient, { gcTime: 10, mutationFn: (input: number) => Promise.resolve(input), }) const unsubscribe = observer.subscribe(() => undefined) expect(queryClient.getMutationCache().getAll()).toHaveLength(0) observer.mutate(1) expect(queryClient.getMutationCache().getAll()).toHaveLength(1) await sleep(10) expect(queryClient.getMutationCache().getAll()).toHaveLength(1) unsubscribe() expect(queryClient.getMutationCache().getAll()).toHaveLength(1) await sleep(10) await waitFor(() => { expect(queryClient.getMutationCache().getAll()).toHaveLength(0) }) }) test('should be garbage collected later when unsubscribed and mutation is pending', async () => { const queryClient = createQueryClient() const onSuccess = vi.fn() const observer = new MutationObserver(queryClient, { gcTime: 10, mutationFn: async () => { await sleep(20) return 'data' }, onSuccess, }) const unsubscribe = observer.subscribe(() => undefined) observer.mutate(1) unsubscribe() expect(queryClient.getMutationCache().getAll()).toHaveLength(1) await sleep(10) // unsubscribe should not remove even though gcTime has elapsed b/c mutation is still pending expect(queryClient.getMutationCache().getAll()).toHaveLength(1) await sleep(10) // should be removed after an additional gcTime wait await waitFor(() => { expect(queryClient.getMutationCache().getAll()).toHaveLength(0) }) expect(onSuccess).toHaveBeenCalledTimes(1) }) test('should call callbacks even with gcTime 0 and mutation still pending', async () => { const queryClient = createQueryClient() const onSuccess = vi.fn() const observer = new MutationObserver(queryClient, { gcTime: 0, mutationFn: async () => { return 'data' }, onSuccess, }) const unsubscribe = observer.subscribe(() => undefined) observer.mutate(1) unsubscribe() await waitFor(() => { expect(queryClient.getMutationCache().getAll()).toHaveLength(0) }) expect(onSuccess).toHaveBeenCalledTimes(1) }) }) })
3,874
0
petrpan-code/TanStack/query/packages/query-core/src
petrpan-code/TanStack/query/packages/query-core/src/tests/mutationObserver.test.tsx
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { waitFor } from '@testing-library/react' import { MutationObserver } from '..' import { createQueryClient, sleep } from './utils' import type { QueryClient } from '..' describe('mutationObserver', () => { let queryClient: QueryClient beforeEach(() => { queryClient = createQueryClient() queryClient.mount() }) afterEach(() => { queryClient.clear() }) test('onUnsubscribe should not remove the current mutation observer if there is still a subscription', async () => { const mutation = new MutationObserver(queryClient, { mutationFn: async (text: string) => { await sleep(20) return text }, }) const subscription1Handler = vi.fn() const subscription2Handler = vi.fn() const unsubscribe1 = mutation.subscribe(subscription1Handler) const unsubscribe2 = mutation.subscribe(subscription2Handler) mutation.mutate('input') unsubscribe1() await waitFor(() => { // 1 call: loading expect(subscription1Handler).toBeCalledTimes(1) // 2 calls: loading, success expect(subscription2Handler).toBeCalledTimes(2) }) // Clean-up unsubscribe2() }) })
3,875
0
petrpan-code/TanStack/query/packages/query-core/src
petrpan-code/TanStack/query/packages/query-core/src/tests/mutations.test.tsx
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { waitFor } from '@testing-library/react' import { MutationObserver } from '../mutationObserver' import { createQueryClient, executeMutation, queryKey, sleep } from './utils' import type { QueryClient } from '..' import type { MutationState } from '../mutation' describe('mutations', () => { let queryClient: QueryClient beforeEach(() => { queryClient = createQueryClient() queryClient.mount() }) afterEach(() => { queryClient.clear() }) test('mutate should accept null values', async () => { let variables const mutation = new MutationObserver(queryClient, { mutationFn: async (vars: unknown) => { variables = vars return vars }, }) await mutation.mutate(null) expect(variables).toBe(null) }) test('setMutationDefaults should be able to set defaults', async () => { const key = queryKey() const fn = vi.fn() queryClient.setMutationDefaults(key, { mutationFn: fn, }) await executeMutation( queryClient, { mutationKey: key, }, 'vars', ) expect(fn).toHaveBeenCalledTimes(1) expect(fn).toHaveBeenCalledWith('vars') }) test('mutation should set correct success states', async () => { const mutation = new MutationObserver(queryClient, { mutationFn: async (text: string) => { await sleep(10) return text }, onMutate: (text) => text, }) expect(mutation.getCurrentResult()).toEqual({ context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null, isError: false, isIdle: true, isPending: false, isPaused: false, isSuccess: false, mutate: expect.any(Function), reset: expect.any(Function), status: 'idle', variables: undefined, submittedAt: 0, }) const states: Array<MutationState<string, unknown, string, string>> = [] mutation.subscribe((state) => { states.push(state) }) mutation.mutate('todo') await sleep(0) expect(states[0]).toEqual({ context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null, isError: false, isIdle: false, isPending: true, isPaused: false, isSuccess: false, mutate: expect.any(Function), reset: expect.any(Function), status: 'pending', variables: 'todo', submittedAt: expect.any(Number), }) await sleep(5) expect(states[1]).toEqual({ context: 'todo', data: undefined, error: null, failureCount: 0, failureReason: null, isError: false, isIdle: false, isPending: true, isPaused: false, isSuccess: false, mutate: expect.any(Function), reset: expect.any(Function), status: 'pending', variables: 'todo', submittedAt: expect.any(Number), }) await sleep(20) expect(states[2]).toEqual({ context: 'todo', data: 'todo', error: null, failureCount: 0, failureReason: null, isError: false, isIdle: false, isPending: false, isPaused: false, isSuccess: true, mutate: expect.any(Function), reset: expect.any(Function), status: 'success', variables: 'todo', submittedAt: expect.any(Number), }) }) test('mutation should set correct error states', async () => { const mutation = new MutationObserver(queryClient, { mutationFn: async (_: string) => { await sleep(20) return Promise.reject(new Error('err')) }, onMutate: (text) => text, retry: 1, retryDelay: 1, }) const states: Array<MutationState<string, unknown, string, string>> = [] mutation.subscribe((state) => { states.push(state) }) mutation.mutate('todo').catch(() => undefined) await sleep(0) expect(states[0]).toEqual({ context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null, isError: false, isIdle: false, isPending: true, isPaused: false, isSuccess: false, mutate: expect.any(Function), reset: expect.any(Function), status: 'pending', variables: 'todo', submittedAt: expect.any(Number), }) await sleep(10) expect(states[1]).toEqual({ context: 'todo', data: undefined, error: null, failureCount: 0, failureReason: null, isError: false, isIdle: false, isPending: true, isPaused: false, isSuccess: false, mutate: expect.any(Function), reset: expect.any(Function), status: 'pending', variables: 'todo', submittedAt: expect.any(Number), }) await sleep(20) expect(states[2]).toEqual({ context: 'todo', data: undefined, error: null, failureCount: 1, failureReason: new Error('err'), isError: false, isIdle: false, isPending: true, isPaused: false, isSuccess: false, mutate: expect.any(Function), reset: expect.any(Function), status: 'pending', variables: 'todo', submittedAt: expect.any(Number), }) await sleep(30) expect(states[3]).toEqual({ context: 'todo', data: undefined, error: new Error('err'), failureCount: 2, failureReason: new Error('err'), isError: true, isIdle: false, isPending: false, isPaused: false, isSuccess: false, mutate: expect.any(Function), reset: expect.any(Function), status: 'error', variables: 'todo', submittedAt: expect.any(Number), }) }) test('should be able to restore a mutation', async () => { const key = queryKey() const onMutate = vi.fn() const onSuccess = vi.fn() const onSettled = vi.fn() queryClient.setMutationDefaults(key, { mutationFn: async (text: string) => text, onMutate, onSuccess, onSettled, }) const mutation = queryClient .getMutationCache() .build<string, unknown, string, string>( queryClient, { mutationKey: key, }, { context: 'todo', data: undefined, error: null, failureCount: 1, failureReason: 'err', isPaused: true, status: 'pending', variables: 'todo', submittedAt: 1, }, ) expect(mutation.state).toEqual({ context: 'todo', data: undefined, error: null, failureCount: 1, failureReason: 'err', isPaused: true, status: 'pending', variables: 'todo', submittedAt: 1, }) await queryClient.resumePausedMutations() expect(mutation.state).toEqual({ context: 'todo', data: 'todo', error: null, failureCount: 0, failureReason: null, isPaused: false, status: 'success', variables: 'todo', submittedAt: 1, }) expect(onMutate).not.toHaveBeenCalled() expect(onSuccess).toHaveBeenCalled() expect(onSettled).toHaveBeenCalled() }) test('addObserver should not add an existing observer', async () => { const mutationCache = queryClient.getMutationCache() const observer = new MutationObserver(queryClient, {}) const currentMutation = mutationCache.build(queryClient, {}) const fn = vi.fn() const unsubscribe = mutationCache.subscribe((event) => { fn(event.type) }) currentMutation.addObserver(observer) currentMutation.addObserver(observer) expect(fn).toHaveBeenCalledTimes(1) expect(fn).toHaveBeenCalledWith('observerAdded') unsubscribe() }) test('mutate should throw an error if no mutationFn found', async () => { const mutation = new MutationObserver(queryClient, { mutationFn: undefined, retry: false, }) let error: any try { await mutation.mutate() } catch (err) { error = err } expect(error).toEqual(new Error('No mutationFn found')) }) test('mutate update the mutation state even without an active subscription', async () => { const onSuccess = vi.fn() const onSettled = vi.fn() const mutation = new MutationObserver(queryClient, { mutationFn: async () => { return 'update' }, }) await mutation.mutate(undefined, { onSuccess, onSettled }) expect(mutation.getCurrentResult().data).toEqual('update') expect(onSuccess).not.toHaveBeenCalled() expect(onSettled).not.toHaveBeenCalled() }) test('mutate update the mutation state even without an active subscription', async () => { const onSuccess = vi.fn() const onSettled = vi.fn() const mutation = new MutationObserver(queryClient, { mutationFn: async () => { return 'update' }, }) await mutation.mutate(undefined, { onSuccess, onSettled }) expect(mutation.getCurrentResult().data).toEqual('update') expect(onSuccess).not.toHaveBeenCalled() expect(onSettled).not.toHaveBeenCalled() }) test('mutation callbacks should see updated options', async () => { const onSuccess = vi.fn() const mutation = new MutationObserver(queryClient, { mutationFn: async () => { sleep(100) return 'update' }, onSuccess: () => { onSuccess(1) }, }) void mutation.mutate() mutation.setOptions({ mutationFn: async () => { sleep(100) return 'update' }, onSuccess: () => { onSuccess(2) }, }) await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1)) expect(onSuccess).toHaveBeenCalledWith(2) }) })
3,876
0
petrpan-code/TanStack/query/packages/query-core/src
petrpan-code/TanStack/query/packages/query-core/src/tests/notifyManager.test.tsx
import { describe, expect, it, vi } from 'vitest' import { createNotifyManager } from '../notifyManager' import { sleep } from './utils' describe('notifyManager', () => { it('should use default notifyFn', async () => { const notifyManagerTest = createNotifyManager() const callbackSpy = vi.fn() notifyManagerTest.schedule(callbackSpy) await sleep(1) expect(callbackSpy).toHaveBeenCalled() }) it('should use default batchNotifyFn', async () => { const notifyManagerTest = createNotifyManager() const callbackScheduleSpy = vi .fn() .mockImplementation(async () => await sleep(20)) const callbackBatchLevel2Spy = vi.fn().mockImplementation(async () => { notifyManagerTest.schedule(callbackScheduleSpy) }) const callbackBatchLevel1Spy = vi.fn().mockImplementation(async () => { notifyManagerTest.batch(callbackBatchLevel2Spy) }) notifyManagerTest.batch(callbackBatchLevel1Spy) await sleep(30) expect(callbackBatchLevel1Spy).toHaveBeenCalledTimes(1) expect(callbackBatchLevel2Spy).toHaveBeenCalledTimes(1) expect(callbackScheduleSpy).toHaveBeenCalledTimes(1) }) it('should notify if error is thrown', async () => { const notifyManagerTest = createNotifyManager() const notifySpy = vi.fn() notifyManagerTest.setNotifyFunction(notifySpy) try { notifyManagerTest.batch(() => { notifyManagerTest.schedule(vi.fn) throw new Error('Foo') }) } catch {} // needed for scheduleMicroTask to kick in await sleep(1) expect(notifySpy).toHaveBeenCalledTimes(1) }) it('typedefs should catch proper signatures', async () => { const notifyManagerTest = createNotifyManager() // we define some fn with its signature: const fn: (a: string, b: number) => string = (a, b) => a + b //now somefn expect to be called with args [a: string, b: number] const someFn = notifyManagerTest.batchCalls(fn) someFn('im happy', 4) //@ts-expect-error someFn('im not happy', false) }) })
3,877
0
petrpan-code/TanStack/query/packages/query-core/src
petrpan-code/TanStack/query/packages/query-core/src/tests/onlineManager.test.tsx
import { beforeEach, describe, expect, test, vi } from 'vitest' import { OnlineManager } from '../onlineManager' import { setIsServer, sleep } from './utils' describe('onlineManager', () => { let onlineManager: OnlineManager beforeEach(() => { onlineManager = new OnlineManager() }) test('isOnline should return true if navigator is undefined', () => { const navigatorSpy = vi.spyOn(globalThis, 'navigator', 'get') // Force navigator to be undefined //@ts-expect-error navigatorSpy.mockImplementation(() => undefined) expect(onlineManager.isOnline()).toBeTruthy() navigatorSpy.mockRestore() }) test('isOnline should return true if navigator.onLine is true', () => { const navigatorSpy = vi.spyOn(navigator, 'onLine', 'get') navigatorSpy.mockImplementation(() => true) expect(onlineManager.isOnline()).toBeTruthy() navigatorSpy.mockRestore() }) test('setEventListener should use online boolean arg', async () => { let count = 0 const setup = (setOnline: (online: boolean) => void) => { setTimeout(() => { count++ setOnline(false) }, 20) return () => void 0 } onlineManager.setEventListener(setup) await sleep(30) expect(count).toEqual(1) expect(onlineManager.isOnline()).toBeFalsy() }) test('setEventListener should call previous remove handler when replacing an event listener', () => { const remove1Spy = vi.fn() const remove2Spy = vi.fn() onlineManager.setEventListener(() => remove1Spy) onlineManager.setEventListener(() => remove2Spy) expect(remove1Spy).toHaveBeenCalledTimes(1) expect(remove2Spy).not.toHaveBeenCalled() }) test('cleanup (removeEventListener) should not be called if window is not defined', async () => { const restoreIsServer = setIsServer(true) const removeEventListenerSpy = vi.spyOn(globalThis, 'removeEventListener') const unsubscribe = onlineManager.subscribe(() => undefined) unsubscribe() expect(removeEventListenerSpy).not.toHaveBeenCalled() restoreIsServer() }) test('cleanup (removeEventListener) should not be called if window.addEventListener is not defined', async () => { const { addEventListener } = globalThis.window // @ts-expect-error globalThis.window.addEventListener = undefined const removeEventListenerSpy = vi.spyOn(globalThis, 'removeEventListener') const unsubscribe = onlineManager.subscribe(() => undefined) unsubscribe() expect(removeEventListenerSpy).not.toHaveBeenCalled() globalThis.window.addEventListener = addEventListener }) test('it should replace default window listener when a new event listener is set', async () => { const addEventListenerSpy = vi.spyOn(globalThis.window, 'addEventListener') const removeEventListenerSpy = vi.spyOn( globalThis.window, 'removeEventListener', ) // Should set the default event listener with window event listeners const unsubscribe = onlineManager.subscribe(() => undefined) expect(addEventListenerSpy).toHaveBeenCalledTimes(2) // Should replace the window default event listener by a new one // and it should call window.removeEventListener twice onlineManager.setEventListener(() => { return () => void 0 }) expect(removeEventListenerSpy).toHaveBeenCalledTimes(2) unsubscribe() addEventListenerSpy.mockRestore() removeEventListenerSpy.mockRestore() }) test('should call removeEventListener when last listener unsubscribes', () => { const addEventListenerSpy = vi.spyOn(globalThis.window, 'addEventListener') const removeEventListenerSpy = vi.spyOn( globalThis.window, 'removeEventListener', ) const unsubscribe1 = onlineManager.subscribe(() => undefined) const unsubscribe2 = onlineManager.subscribe(() => undefined) expect(addEventListenerSpy).toHaveBeenCalledTimes(2) // online + offline unsubscribe1() expect(removeEventListenerSpy).toHaveBeenCalledTimes(0) unsubscribe2() expect(removeEventListenerSpy).toHaveBeenCalledTimes(2) // online + offline }) test('should keep setup function even if last listener unsubscribes', () => { const setupSpy = vi.fn().mockImplementation(() => () => undefined) onlineManager.setEventListener(setupSpy) const unsubscribe1 = onlineManager.subscribe(() => undefined) expect(setupSpy).toHaveBeenCalledTimes(1) unsubscribe1() const unsubscribe2 = onlineManager.subscribe(() => undefined) expect(setupSpy).toHaveBeenCalledTimes(2) unsubscribe2() }) test('should call listeners when setOnline is called', () => { const listener = vi.fn() onlineManager.subscribe(listener) onlineManager.setOnline(false) onlineManager.setOnline(false) expect(listener).toHaveBeenNthCalledWith(1, false) onlineManager.setOnline(true) onlineManager.setOnline(true) expect(listener).toHaveBeenCalledTimes(2) expect(listener).toHaveBeenNthCalledWith(2, true) }) })
3,878
0
petrpan-code/TanStack/query/packages/query-core/src
petrpan-code/TanStack/query/packages/query-core/src/tests/queriesObserver.test.tsx
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { waitFor } from '@testing-library/react' import { QueriesObserver } from '..' import { createQueryClient, queryKey, sleep } from './utils' import type { QueryClient, QueryObserverResult } from '..' describe('queriesObserver', () => { let queryClient: QueryClient beforeEach(() => { queryClient = createQueryClient() queryClient.mount() }) afterEach(() => { queryClient.clear() }) test('should return an array with all query results', async () => { const key1 = queryKey() const key2 = queryKey() const queryFn1 = vi.fn().mockReturnValue(1) const queryFn2 = vi.fn().mockReturnValue(2) const observer = new QueriesObserver(queryClient, [ { queryKey: key1, queryFn: queryFn1 }, { queryKey: key2, queryFn: queryFn2 }, ]) let observerResult const unsubscribe = observer.subscribe((result) => { observerResult = result }) await sleep(1) unsubscribe() expect(observerResult).toMatchObject([{ data: 1 }, { data: 2 }]) }) test('should still return value for undefined query key', async () => { const consoleMock = vi.spyOn(console, 'error') consoleMock.mockImplementation(() => undefined) const key1 = queryKey() const queryFn1 = vi.fn().mockReturnValue(1) const queryFn2 = vi.fn().mockReturnValue(2) const observer = new QueriesObserver(queryClient, [ { queryKey: key1, queryFn: queryFn1 }, { queryKey: undefined, queryFn: queryFn2 }, ]) let observerResult const unsubscribe = observer.subscribe((result) => { observerResult = result }) await sleep(1) unsubscribe() expect(observerResult).toMatchObject([{ data: 1 }, { data: 2 }]) expect(consoleMock).toHaveBeenCalledTimes(1) expect(consoleMock).toHaveBeenCalledWith( "As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']", ) consoleMock.mockRestore() }) test('should update when a query updates', async () => { const key1 = queryKey() const key2 = queryKey() const queryFn1 = vi.fn().mockReturnValue(1) const queryFn2 = vi.fn().mockReturnValue(2) const observer = new QueriesObserver(queryClient, [ { queryKey: key1, queryFn: queryFn1 }, { queryKey: key2, queryFn: queryFn2 }, ]) const results: Array<Array<QueryObserverResult>> = [] results.push(observer.getCurrentResult()) const unsubscribe = observer.subscribe((result) => { results.push(result) }) await sleep(1) queryClient.setQueryData(key2, 3) await sleep(1) unsubscribe() expect(results.length).toBe(6) expect(results[0]).toMatchObject([ { status: 'pending', fetchStatus: 'idle', data: undefined }, { status: 'pending', fetchStatus: 'idle', data: undefined }, ]) expect(results[1]).toMatchObject([ { status: 'pending', fetchStatus: 'fetching', data: undefined }, { status: 'pending', fetchStatus: 'idle', data: undefined }, ]) expect(results[2]).toMatchObject([ { status: 'pending', fetchStatus: 'fetching', data: undefined }, { status: 'pending', fetchStatus: 'fetching', data: undefined }, ]) expect(results[3]).toMatchObject([ { status: 'success', data: 1 }, { status: 'pending', fetchStatus: 'fetching', data: undefined }, ]) expect(results[4]).toMatchObject([ { status: 'success', data: 1 }, { status: 'success', data: 2 }, ]) expect(results[5]).toMatchObject([ { status: 'success', data: 1 }, { status: 'success', data: 3 }, ]) }) test('should update when a query is removed', async () => { const key1 = queryKey() const key2 = queryKey() const queryFn1 = vi.fn().mockReturnValue(1) const queryFn2 = vi.fn().mockReturnValue(2) const observer = new QueriesObserver(queryClient, [ { queryKey: key1, queryFn: queryFn1 }, { queryKey: key2, queryFn: queryFn2 }, ]) const results: Array<Array<QueryObserverResult>> = [] results.push(observer.getCurrentResult()) const unsubscribe = observer.subscribe((result) => { results.push(result) }) await sleep(1) observer.setQueries([{ queryKey: key2, queryFn: queryFn2 }]) await sleep(1) const queryCache = queryClient.getQueryCache() expect(queryCache.find({ queryKey: key1, type: 'active' })).toBeUndefined() expect(queryCache.find({ queryKey: key2, type: 'active' })).toBeDefined() unsubscribe() expect(queryCache.find({ queryKey: key1, type: 'active' })).toBeUndefined() expect(queryCache.find({ queryKey: key2, type: 'active' })).toBeUndefined() expect(results.length).toBe(6) expect(results[0]).toMatchObject([ { status: 'pending', fetchStatus: 'idle', data: undefined }, { status: 'pending', fetchStatus: 'idle', data: undefined }, ]) expect(results[1]).toMatchObject([ { status: 'pending', fetchStatus: 'fetching', data: undefined }, { status: 'pending', fetchStatus: 'idle', data: undefined }, ]) expect(results[2]).toMatchObject([ { status: 'pending', fetchStatus: 'fetching', data: undefined }, { status: 'pending', fetchStatus: 'fetching', data: undefined }, ]) expect(results[3]).toMatchObject([ { status: 'success', data: 1 }, { status: 'pending', fetchStatus: 'fetching', data: undefined }, ]) expect(results[4]).toMatchObject([ { status: 'success', data: 1 }, { status: 'success', data: 2 }, ]) expect(results[5]).toMatchObject([{ status: 'success', data: 2 }]) }) test('should update when a query changed position', async () => { const key1 = queryKey() const key2 = queryKey() const queryFn1 = vi.fn().mockReturnValue(1) const queryFn2 = vi.fn().mockReturnValue(2) const observer = new QueriesObserver(queryClient, [ { queryKey: key1, queryFn: queryFn1 }, { queryKey: key2, queryFn: queryFn2 }, ]) const results: Array<Array<QueryObserverResult>> = [] results.push(observer.getCurrentResult()) const unsubscribe = observer.subscribe((result) => { results.push(result) }) await sleep(1) observer.setQueries([ { queryKey: key2, queryFn: queryFn2 }, { queryKey: key1, queryFn: queryFn1 }, ]) await sleep(1) unsubscribe() expect(results.length).toBe(6) expect(results[0]).toMatchObject([ { status: 'pending', fetchStatus: 'idle', data: undefined }, { status: 'pending', fetchStatus: 'idle', data: undefined }, ]) expect(results[1]).toMatchObject([ { status: 'pending', fetchStatus: 'fetching', data: undefined }, { status: 'pending', fetchStatus: 'idle', data: undefined }, ]) expect(results[2]).toMatchObject([ { status: 'pending', fetchStatus: 'fetching', data: undefined }, { status: 'pending', fetchStatus: 'fetching', data: undefined }, ]) expect(results[3]).toMatchObject([ { status: 'success', data: 1 }, { status: 'pending', fetchStatus: 'fetching', data: undefined }, ]) expect(results[4]).toMatchObject([ { status: 'success', data: 1 }, { status: 'success', data: 2 }, ]) expect(results[5]).toMatchObject([ { status: 'success', data: 2 }, { status: 'success', data: 1 }, ]) }) test('should not update when nothing has changed', async () => { const key1 = queryKey() const key2 = queryKey() const queryFn1 = vi.fn().mockReturnValue(1) const queryFn2 = vi.fn().mockReturnValue(2) const observer = new QueriesObserver(queryClient, [ { queryKey: key1, queryFn: queryFn1 }, { queryKey: key2, queryFn: queryFn2 }, ]) const results: Array<Array<QueryObserverResult>> = [] results.push(observer.getCurrentResult()) const unsubscribe = observer.subscribe((result) => { results.push(result) }) await sleep(1) observer.setQueries([ { queryKey: key1, queryFn: queryFn1 }, { queryKey: key2, queryFn: queryFn2 }, ]) await sleep(1) unsubscribe() expect(results.length).toBe(5) expect(results[0]).toMatchObject([ { status: 'pending', fetchStatus: 'idle', data: undefined }, { status: 'pending', fetchStatus: 'idle', data: undefined }, ]) expect(results[1]).toMatchObject([ { status: 'pending', fetchStatus: 'fetching', data: undefined }, { status: 'pending', fetchStatus: 'idle', data: undefined }, ]) expect(results[2]).toMatchObject([ { status: 'pending', fetchStatus: 'fetching', data: undefined }, { status: 'pending', fetchStatus: 'fetching', data: undefined }, ]) expect(results[3]).toMatchObject([ { status: 'success', data: 1 }, { status: 'pending', fetchStatus: 'fetching', data: undefined }, ]) expect(results[4]).toMatchObject([ { status: 'success', data: 1 }, { status: 'success', data: 2 }, ]) }) test('should trigger all fetches when subscribed', async () => { const key1 = queryKey() const key2 = queryKey() const queryFn1 = vi.fn().mockReturnValue(1) const queryFn2 = vi.fn().mockReturnValue(2) const observer = new QueriesObserver(queryClient, [ { queryKey: key1, queryFn: queryFn1 }, { queryKey: key2, queryFn: queryFn2 }, ]) const unsubscribe = observer.subscribe(() => undefined) await sleep(1) unsubscribe() expect(queryFn1).toHaveBeenCalledTimes(1) expect(queryFn2).toHaveBeenCalledTimes(1) }) test('should not destroy the observer if there is still a subscription', async () => { const key1 = queryKey() const observer = new QueriesObserver(queryClient, [ { queryKey: key1, queryFn: async () => { await sleep(20) return 1 }, }, ]) const subscription1Handler = vi.fn() const subscription2Handler = vi.fn() const unsubscribe1 = observer.subscribe(subscription1Handler) const unsubscribe2 = observer.subscribe(subscription2Handler) unsubscribe1() await waitFor(() => { // 1 call: pending expect(subscription1Handler).toBeCalledTimes(1) // 1 call: success expect(subscription2Handler).toBeCalledTimes(1) }) // Clean-up unsubscribe2() }) })
3,879
0
petrpan-code/TanStack/query/packages/query-core/src
petrpan-code/TanStack/query/packages/query-core/src/tests/query.test.tsx
import { afterEach, beforeEach, describe, expect, it, test, vi } from 'vitest' import { waitFor } from '@testing-library/react' import { QueryObserver, isCancelledError, onlineManager } from '..' import { createQueryClient, mockVisibilityState, queryKey, setIsServer, sleep, } from './utils' import type { QueryCache, QueryClient, QueryFunctionContext, QueryObserverResult, } from '..' describe('query', () => { let queryClient: QueryClient let queryCache: QueryCache beforeEach(() => { queryClient = createQueryClient() queryCache = queryClient.getQueryCache() queryClient.mount() }) afterEach(() => { queryClient.clear() }) test('should use the longest garbage collection time it has seen', async () => { const key = queryKey() await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data', gcTime: 100, }) await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data', gcTime: 200, }) await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data', gcTime: 10, }) const query = queryCache.find({ queryKey: key })! expect(query.gcTime).toBe(200) }) it('should continue retry after focus regain and resolve all promises', async () => { const key = queryKey() // make page unfocused const visibilityMock = mockVisibilityState('hidden') let count = 0 let result const promise = queryClient.fetchQuery({ queryKey: key, queryFn: async () => { count++ if (count === 3) { return `data${count}` } throw new Error(`error${count}`) }, retry: 3, retryDelay: 1, }) promise.then((data) => { result = data }) // Check if we do not have a result expect(result).toBeUndefined() // Check if the query is really paused await sleep(50) expect(result).toBeUndefined() // Reset visibilityState to original value visibilityMock.mockRestore() window.dispatchEvent(new Event('visibilitychange')) // There should not be a result yet expect(result).toBeUndefined() // By now we should have a value await sleep(50) expect(result).toBe('data3') }) it('should continue retry after reconnect and resolve all promises', async () => { const key = queryKey() onlineManager.setOnline(false) let count = 0 let result const promise = queryClient.fetchQuery({ queryKey: key, queryFn: async () => { count++ if (count === 3) { return `data${count}` } throw new Error(`error${count}`) }, retry: 3, retryDelay: 1, }) promise.then((data) => { result = data }) // Check if we do not have a result expect(result).toBeUndefined() // Check if the query is really paused await sleep(50) expect(result).toBeUndefined() // Reset navigator to original value onlineManager.setOnline(true) // There should not be a result yet expect(result).toBeUndefined() // Promise should eventually be resolved await promise expect(result).toBe('data3') }) it('should throw a CancelledError when a paused query is cancelled', async () => { const key = queryKey() // make page unfocused const visibilityMock = mockVisibilityState('hidden') let count = 0 let result const promise = queryClient.fetchQuery({ queryKey: key, queryFn: async (): Promise<unknown> => { count++ throw new Error(`error${count}`) }, retry: 3, retryDelay: 1, }) promise.catch((data) => { result = data }) const query = queryCache.find({ queryKey: key })! // Check if the query is really paused await sleep(50) expect(result).toBeUndefined() // Cancel query query.cancel() // Check if the error is set to the cancelled error try { await promise } catch { expect(isCancelledError(result)).toBe(true) } finally { // Reset visibilityState to original value visibilityMock.mockRestore() } }) test('should provide context to queryFn', async () => { const key = queryKey() const queryFn = vi .fn< [QueryFunctionContext<ReturnType<typeof queryKey>>], Promise<'data'> >() .mockResolvedValue('data') queryClient.prefetchQuery({ queryKey: key, queryFn }) await sleep(10) expect(queryFn).toHaveBeenCalledTimes(1) const args = queryFn.mock.calls[0]![0] expect(args).toBeDefined() // @ts-expect-error page param should be undefined expect(args.pageParam).toBeUndefined() expect(args.queryKey).toEqual(key) expect(args.signal).toBeInstanceOf(AbortSignal) }) test('should continue if cancellation is not supported and signal is not consumed', async () => { const key = queryKey() queryClient.prefetchQuery({ queryKey: key, queryFn: async () => { await sleep(100) return 'data' }, }) await sleep(10) // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed const observer = new QueryObserver(queryClient, { queryKey: key, enabled: false, }) const unsubscribe = observer.subscribe(() => undefined) unsubscribe() await sleep(100) const query = queryCache.find({ queryKey: key })! expect(query.state).toMatchObject({ data: 'data', status: 'success', dataUpdateCount: 1, }) }) test('should not continue when last observer unsubscribed if the signal was consumed', async () => { const key = queryKey() queryClient.prefetchQuery({ queryKey: key, queryFn: async ({ signal }) => { await sleep(100) return signal.aborted ? 'aborted' : 'data' }, }) await sleep(10) // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed const observer = new QueryObserver(queryClient, { queryKey: key, enabled: false, }) const unsubscribe = observer.subscribe(() => undefined) unsubscribe() await sleep(100) const query = queryCache.find({ queryKey: key })! expect(query.state).toMatchObject({ data: undefined, status: 'pending', fetchStatus: 'idle', }) }) test('should provide an AbortSignal to the queryFn that provides info about the cancellation state', async () => { const key = queryKey() const queryFn = vi.fn< [QueryFunctionContext<ReturnType<typeof queryKey>>], Promise<unknown> >() const onAbort = vi.fn() const abortListener = vi.fn() let error queryFn.mockImplementation(async ({ signal }) => { signal.onabort = onAbort signal.addEventListener('abort', abortListener) await sleep(10) signal.onabort = null signal.removeEventListener('abort', abortListener) throw new Error() }) const promise = queryClient.fetchQuery({ queryKey: key, queryFn, retry: 3, retryDelay: 10, }) promise.catch((e) => { error = e }) const query = queryCache.find({ queryKey: key })! expect(queryFn).toHaveBeenCalledTimes(1) const signal = queryFn.mock.calls[0]![0].signal expect(signal.aborted).toBe(false) expect(onAbort).not.toHaveBeenCalled() expect(abortListener).not.toHaveBeenCalled() query.cancel() await sleep(100) expect(signal.aborted).toBe(true) expect(onAbort).toHaveBeenCalledTimes(1) expect(abortListener).toHaveBeenCalledTimes(1) expect(isCancelledError(error)).toBe(true) }) test('should not continue if explicitly cancelled', async () => { const key = queryKey() const queryFn = vi.fn<Array<unknown>, unknown>() queryFn.mockImplementation(async () => { await sleep(10) throw new Error() }) let error const promise = queryClient.fetchQuery({ queryKey: key, queryFn, retry: 3, retryDelay: 10, }) promise.catch((e) => { error = e }) const query = queryCache.find({ queryKey: key })! query.cancel() await sleep(100) expect(queryFn).toHaveBeenCalledTimes(1) expect(isCancelledError(error)).toBe(true) }) test('should not error if reset while pending', async () => { const key = queryKey() const queryFn = vi.fn<Array<unknown>, unknown>() queryFn.mockImplementation(async () => { await sleep(10) throw new Error() }) queryClient.fetchQuery({ queryKey: key, queryFn, retry: 3, retryDelay: 10 }) // Ensure the query is pending const query = queryCache.find({ queryKey: key })! expect(query.state.status).toBe('pending') // Reset the query while it is pending query.reset() await sleep(100) // The query should expect(queryFn).toHaveBeenCalledTimes(1) // have been called, expect(query.state.error).toBe(null) // not have an error, and expect(query.state.fetchStatus).toBe('idle') // not be loading any longer }) test('should be able to refetch a cancelled query', async () => { const key = queryKey() const queryFn = vi.fn<Array<unknown>, unknown>() queryFn.mockImplementation(async () => { await sleep(50) return 'data' }) queryClient.prefetchQuery({ queryKey: key, queryFn }) const query = queryCache.find({ queryKey: key })! await sleep(10) query.cancel() await sleep(100) expect(queryFn).toHaveBeenCalledTimes(1) expect(isCancelledError(query.state.error)).toBe(true) const result = await query.fetch() expect(result).toBe('data') expect(query.state.error).toBe(null) expect(queryFn).toHaveBeenCalledTimes(2) }) test('cancelling a resolved query should not have any effect', async () => { const key = queryKey() await queryClient.prefetchQuery({ queryKey: key, queryFn: async () => 'data', }) const query = queryCache.find({ queryKey: key })! query.cancel() await sleep(10) expect(query.state.data).toBe('data') }) test('cancelling a rejected query should not have any effect', async () => { const key = queryKey() const error = new Error('error') await queryClient.prefetchQuery({ queryKey: key, queryFn: async (): Promise<unknown> => { throw error }, }) const query = queryCache.find({ queryKey: key })! query.cancel() await sleep(10) expect(query.state.error).toBe(error) expect(isCancelledError(query.state.error)).toBe(false) }) test('the previous query status should be kept when refetching', async () => { const key = queryKey() await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' }) const query = queryCache.find({ queryKey: key })! expect(query.state.status).toBe('success') await queryClient.prefetchQuery({ queryKey: key, queryFn: () => Promise.reject<string>('reject'), retry: false, }) expect(query.state.status).toBe('error') queryClient.prefetchQuery({ queryKey: key, queryFn: async () => { await sleep(10) return Promise.reject<unknown>('reject') }, retry: false, }) expect(query.state.status).toBe('error') await sleep(100) expect(query.state.status).toBe('error') }) test('queries with gcTime 0 should be removed immediately after unsubscribing', async () => { const key = queryKey() let count = 0 const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => { count++ return 'data' }, gcTime: 0, staleTime: Infinity, }) const unsubscribe1 = observer.subscribe(() => undefined) unsubscribe1() await waitFor(() => expect(queryCache.find({ queryKey: key })).toBeUndefined(), ) const unsubscribe2 = observer.subscribe(() => undefined) unsubscribe2() await waitFor(() => expect(queryCache.find({ queryKey: key })).toBeUndefined(), ) expect(count).toBe(1) }) test('should be garbage collected when unsubscribed to', async () => { const key = queryKey() const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: async () => 'data', gcTime: 0, }) expect(queryCache.find({ queryKey: key })).toBeDefined() const unsubscribe = observer.subscribe(() => undefined) expect(queryCache.find({ queryKey: key })).toBeDefined() unsubscribe() await waitFor(() => expect(queryCache.find({ queryKey: key })).toBeUndefined(), ) }) test('should be garbage collected later when unsubscribed and query is fetching', async () => { const key = queryKey() const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: async () => { await sleep(20) return 'data' }, gcTime: 10, }) const unsubscribe = observer.subscribe(() => undefined) await sleep(20) expect(queryCache.find({ queryKey: key })).toBeDefined() observer.refetch() unsubscribe() await sleep(10) // unsubscribe should not remove even though gcTime has elapsed b/c query is still fetching expect(queryCache.find({ queryKey: key })).toBeDefined() await sleep(10) // should be removed after an additional staleTime wait await waitFor(() => expect(queryCache.find({ queryKey: key })).toBeUndefined(), ) }) test('should not be garbage collected unless there are no subscribers', async () => { const key = queryKey() const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: async () => 'data', gcTime: 0, }) expect(queryCache.find({ queryKey: key })).toBeDefined() const unsubscribe = observer.subscribe(() => undefined) await sleep(100) expect(queryCache.find({ queryKey: key })).toBeDefined() unsubscribe() await sleep(100) expect(queryCache.find({ queryKey: key })).toBeUndefined() queryClient.setQueryData(key, 'data') await sleep(100) expect(queryCache.find({ queryKey: key })).toBeDefined() }) test('should return proper count of observers', async () => { const key = queryKey() const options = { queryKey: key, queryFn: async () => 'data' } const observer = new QueryObserver(queryClient, options) const observer2 = new QueryObserver(queryClient, options) const observer3 = new QueryObserver(queryClient, options) const query = queryCache.find({ queryKey: key }) expect(query?.getObserversCount()).toEqual(0) const unsubscribe1 = observer.subscribe(() => undefined) const unsubscribe2 = observer2.subscribe(() => undefined) const unsubscribe3 = observer3.subscribe(() => undefined) expect(query?.getObserversCount()).toEqual(3) unsubscribe3() expect(query?.getObserversCount()).toEqual(2) unsubscribe2() expect(query?.getObserversCount()).toEqual(1) unsubscribe1() expect(query?.getObserversCount()).toEqual(0) }) test('stores meta object in query', async () => { const meta = { it: 'works', } const key = queryKey() await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data', meta, }) const query = queryCache.find({ queryKey: key })! expect(query.meta).toBe(meta) expect(query.options.meta).toBe(meta) }) test('updates meta object on change', async () => { const meta = { it: 'works', } const key = queryKey() const queryFn = () => 'data' await queryClient.prefetchQuery({ queryKey: key, queryFn, meta }) await queryClient.prefetchQuery({ queryKey: key, queryFn, meta: undefined }) const query = queryCache.find({ queryKey: key })! expect(query.meta).toBeUndefined() expect(query.options.meta).toBeUndefined() }) test('can use default meta', async () => { const meta = { it: 'works', } const key = queryKey() const queryFn = () => 'data' queryClient.setQueryDefaults(key, { meta }) await queryClient.prefetchQuery({ queryKey: key, queryFn }) const query = queryCache.find({ queryKey: key })! expect(query.meta).toBe(meta) }) test('provides meta object inside query function', async () => { const meta = { it: 'works', } const queryFn = vi.fn(() => 'data') const key = queryKey() await queryClient.prefetchQuery({ queryKey: key, queryFn, meta }) expect(queryFn).toBeCalledWith( expect.objectContaining({ meta, }), ) }) test('should refetch the observer when online method is called', async () => { const key = queryKey() const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => 'data', }) const refetchSpy = vi.spyOn(observer, 'refetch') const unsubscribe = observer.subscribe(() => undefined) queryCache.onOnline() // Should refetch the observer expect(refetchSpy).toHaveBeenCalledTimes(1) unsubscribe() refetchSpy.mockRestore() }) test('should not add an existing observer', async () => { const key = queryKey() await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' }) const query = queryCache.find({ queryKey: key })! expect(query.getObserversCount()).toEqual(0) const observer = new QueryObserver(queryClient, { queryKey: key, }) expect(query.getObserversCount()).toEqual(0) query.addObserver(observer) expect(query.getObserversCount()).toEqual(1) query.addObserver(observer) expect(query.getObserversCount()).toEqual(1) }) test('should not try to remove an observer that does not exist', async () => { const key = queryKey() await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' }) const query = queryCache.find({ queryKey: key })! const observer = new QueryObserver(queryClient, { queryKey: key, }) expect(query.getObserversCount()).toEqual(0) const notifySpy = vi.spyOn(queryCache, 'notify') expect(() => query.removeObserver(observer)).not.toThrow() expect(notifySpy).not.toHaveBeenCalled() notifySpy.mockRestore() }) test('should not change state on invalidate() if already invalidated', async () => { const key = queryKey() await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' }) const query = queryCache.find({ queryKey: key })! query.invalidate() expect(query.state.isInvalidated).toBeTruthy() const previousState = query.state query.invalidate() expect(query.state).toBe(previousState) }) test('fetch should not dispatch "fetch" query is already fetching', async () => { const key = queryKey() const queryFn = async () => { await sleep(10) return 'data' } const updates: Array<string> = [] await queryClient.prefetchQuery({ queryKey: key, queryFn }) const query = queryCache.find({ queryKey: key })! const unsubscribe = queryClient.getQueryCache().subscribe((event) => { updates.push(event.type) }) void query.fetch({ queryKey: key, queryFn, }) await query.fetch({ queryKey: key, queryFn, }) expect(updates).toEqual([ 'updated', // type: 'fetch' 'updated', // type: 'success' ]) unsubscribe() }) test('fetch should throw an error if the queryFn is not defined', async () => { const key = queryKey() const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: undefined, retry: false, }) const unsubscribe = observer.subscribe(() => undefined) await sleep(10) const query = queryCache.find({ queryKey: key })! expect(observer.getCurrentResult()).toMatchObject({ status: 'error', error: new Error(`Missing queryFn: '${query.queryHash}'`), }) unsubscribe() }) test('fetch should dispatch an error if the queryFn returns undefined', async () => { const consoleMock = vi.spyOn(console, 'error') consoleMock.mockImplementation(() => undefined) const key = queryKey() const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => undefined, retry: false, }) let observerResult: QueryObserverResult<unknown, unknown> | undefined const unsubscribe = observer.subscribe((result) => { observerResult = result }) await sleep(10) const error = new Error(`${JSON.stringify(key)} data is undefined`) expect(observerResult).toMatchObject({ isError: true, error, }) expect(consoleMock).toHaveBeenCalledWith( `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["${key}"]`, ) unsubscribe() consoleMock.mockRestore() }) it('should not retry on the server', async () => { const resetIsServer = setIsServer(true) const key = queryKey() let count = 0 const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => { count++ return Promise.reject(new Error('error')) }, }) await observer.refetch() expect(count).toBe(1) resetIsServer() }) test('constructor should call initialDataUpdatedAt if defined as a function', async () => { const key = queryKey() const initialDataUpdatedAtSpy = vi.fn() await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data', initialData: 'initial', initialDataUpdatedAt: initialDataUpdatedAtSpy, }) expect(initialDataUpdatedAtSpy).toHaveBeenCalled() }) test('queries should be garbage collected even if they never fetched', async () => { const key = queryKey() queryClient.setQueryDefaults(key, { gcTime: 10 }) const fn = vi.fn() const unsubscribe = queryClient.getQueryCache().subscribe(fn) queryClient.setQueryData(key, 'data') await waitFor(() => expect(fn).toHaveBeenCalledWith( expect.objectContaining({ type: 'removed', }), ), ) expect(queryClient.getQueryCache().findAll()).toHaveLength(0) unsubscribe() }) test('should always revert to idle state (#5958)', async () => { let mockedData = [1] const key = queryKey() const queryFn = vi .fn< [QueryFunctionContext<ReturnType<typeof queryKey>>], Promise<unknown> >() .mockImplementation(({ signal }) => { return new Promise((resolve, reject) => { const abortListener = () => { clearTimeout(timerId) reject(signal.reason) } signal.addEventListener('abort', abortListener) const timerId = setTimeout(() => { signal.removeEventListener('abort', abortListener) resolve(mockedData.join(' - ')) }, 50) }) }) const observer = new QueryObserver(queryClient, { queryKey: key, queryFn, }) const unsubscribe = observer.subscribe(() => undefined) await sleep(60) // let it resolve mockedData = [1, 2] // update "server" state in the background queryClient.invalidateQueries({ queryKey: key }) await sleep(1) queryClient.invalidateQueries({ queryKey: key }) await sleep(1) unsubscribe() // unsubscribe to simulate unmount // set up a new observer to simulate a mount of new component const newObserver = new QueryObserver(queryClient, { queryKey: key, queryFn, }) const spy = vi.fn() newObserver.subscribe(({ data }) => spy(data)) await sleep(60) // let it resolve expect(spy).toHaveBeenCalledWith('1 - 2') }) })
3,880
0
petrpan-code/TanStack/query/packages/query-core/src
petrpan-code/TanStack/query/packages/query-core/src/tests/queryCache.test.tsx
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { waitFor } from '@testing-library/react' import { QueryCache, QueryClient, QueryObserver } from '..' import { createQueryClient, queryKey, sleep } from './utils' describe('queryCache', () => { let queryClient: QueryClient let queryCache: QueryCache beforeEach(() => { queryClient = createQueryClient() queryCache = queryClient.getQueryCache() }) afterEach(() => { queryClient.clear() }) describe('subscribe', () => { test('should pass the correct query', async () => { const key = queryKey() const subscriber = vi.fn() const unsubscribe = queryCache.subscribe(subscriber) queryClient.setQueryData(key, 'foo') const query = queryCache.find({ queryKey: key }) await sleep(1) expect(subscriber).toHaveBeenCalledWith({ query, type: 'added' }) unsubscribe() }) test('should notify listeners when new query is added', async () => { const key = queryKey() const callback = vi.fn() queryCache.subscribe(callback) queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' }) await sleep(100) expect(callback).toHaveBeenCalled() }) test('should notify query cache when a query becomes stale', async () => { const key = queryKey() const events: Array<string> = [] const unsubscribe = queryCache.subscribe((event) => { events.push(event.type) }) const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => 'data', staleTime: 10, }) const unsubScribeObserver = observer.subscribe(vi.fn()) await waitFor(() => { expect(events.length).toBe(8) }) expect(events).toEqual([ 'added', // 1. Query added -> loading 'observerResultsUpdated', // 2. Observer result updated -> loading 'observerAdded', // 3. Observer added 'observerResultsUpdated', // 4. Observer result updated -> fetching 'updated', // 5. Query updated -> fetching 'observerResultsUpdated', // 6. Observer result updated -> success 'updated', // 7. Query updated -> success 'observerResultsUpdated', // 8. Observer result updated -> stale ]) unsubscribe() unsubScribeObserver() }) test('should include the queryCache and query when notifying listeners', async () => { const key = queryKey() const callback = vi.fn() queryCache.subscribe(callback) queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' }) const query = queryCache.find({ queryKey: key }) await sleep(100) expect(callback).toHaveBeenCalledWith({ query, type: 'added' }) }) test('should notify subscribers when new query with initialData is added', async () => { const key = queryKey() const callback = vi.fn() queryCache.subscribe(callback) queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data', initialData: 'initial', }) await sleep(100) expect(callback).toHaveBeenCalled() }) test('should be able to limit cache size', async () => { const testCache = new QueryCache() const unsubscribe = testCache.subscribe((event) => { if (event.type === 'added') { if (testCache.getAll().length > 2) { testCache .findAll({ type: 'inactive', predicate: (q) => q !== event.query, }) .forEach((query) => { testCache.remove(query) }) } } }) const testClient = new QueryClient({ queryCache: testCache }) await testClient.prefetchQuery({ queryKey: ['key1'], queryFn: () => 'data1', }) expect(testCache.findAll().length).toBe(1) await testClient.prefetchQuery({ queryKey: ['key2'], queryFn: () => 'data2', }) expect(testCache.findAll().length).toBe(2) await testClient.prefetchQuery({ queryKey: ['key3'], queryFn: () => 'data3', }) expect(testCache.findAll().length).toBe(1) expect(testCache.findAll()[0]!.state.data).toBe('data3') unsubscribe() }) }) describe('find', () => { test('find should filter correctly', async () => { const key = queryKey() await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data1' }) const query = queryCache.find({ queryKey: key })! expect(query).toBeDefined() }) test('find should filter correctly with exact set to false', async () => { const key = queryKey() await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data1' }) const query = queryCache.find({ queryKey: key, exact: false })! expect(query).toBeDefined() }) }) describe('findAll', () => { test('should filter correctly', async () => { const key1 = queryKey() const key2 = queryKey() const keyFetching = queryKey() await queryClient.prefetchQuery({ queryKey: key1, queryFn: () => 'data1', }) await queryClient.prefetchQuery({ queryKey: key2, queryFn: () => 'data2', }) await queryClient.prefetchQuery({ queryKey: [{ a: 'a', b: 'b' }], queryFn: () => 'data3', }) await queryClient.prefetchQuery({ queryKey: ['posts', 1], queryFn: () => 'data4', }) queryClient.invalidateQueries({ queryKey: key2 }) const query1 = queryCache.find({ queryKey: key1 })! const query2 = queryCache.find({ queryKey: key2 })! const query3 = queryCache.find({ queryKey: [{ a: 'a', b: 'b' }] })! const query4 = queryCache.find({ queryKey: ['posts', 1] })! expect(queryCache.findAll({ queryKey: key1 })).toEqual([query1]) // wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array expect(queryCache.findAll({ queryKey: [key1] })).toEqual([]) expect(queryCache.findAll()).toEqual([query1, query2, query3, query4]) expect(queryCache.findAll({})).toEqual([query1, query2, query3, query4]) expect(queryCache.findAll({ queryKey: key1, type: 'inactive' })).toEqual([ query1, ]) expect(queryCache.findAll({ queryKey: key1, type: 'active' })).toEqual([]) expect(queryCache.findAll({ queryKey: key1, stale: true })).toEqual([]) expect(queryCache.findAll({ queryKey: key1, stale: false })).toEqual([ query1, ]) expect( queryCache.findAll({ queryKey: key1, stale: false, type: 'active' }), ).toEqual([]) expect( queryCache.findAll({ queryKey: key1, stale: false, type: 'inactive' }), ).toEqual([query1]) expect( queryCache.findAll({ queryKey: key1, stale: false, type: 'inactive', exact: true, }), ).toEqual([query1]) expect(queryCache.findAll({ queryKey: key2 })).toEqual([query2]) expect(queryCache.findAll({ queryKey: key2, stale: undefined })).toEqual([ query2, ]) expect(queryCache.findAll({ queryKey: key2, stale: true })).toEqual([ query2, ]) expect(queryCache.findAll({ queryKey: key2, stale: false })).toEqual([]) expect(queryCache.findAll({ queryKey: [{ b: 'b' }] })).toEqual([query3]) expect( queryCache.findAll({ queryKey: [{ a: 'a' }], exact: false }), ).toEqual([query3]) expect( queryCache.findAll({ queryKey: [{ a: 'a' }], exact: true }), ).toEqual([]) expect( queryCache.findAll({ queryKey: [{ a: 'a', b: 'b' }], exact: true }), ).toEqual([query3]) expect(queryCache.findAll({ queryKey: [{ a: 'a', b: 'b' }] })).toEqual([ query3, ]) expect( queryCache.findAll({ queryKey: [{ a: 'a', b: 'b', c: 'c' }] }), ).toEqual([]) expect( queryCache.findAll({ queryKey: [{ a: 'a' }], stale: false }), ).toEqual([query3]) expect( queryCache.findAll({ queryKey: [{ a: 'a' }], stale: true }), ).toEqual([]) expect( queryCache.findAll({ queryKey: [{ a: 'a' }], type: 'active' }), ).toEqual([]) expect( queryCache.findAll({ queryKey: [{ a: 'a' }], type: 'inactive' }), ).toEqual([query3]) expect( queryCache.findAll({ predicate: (query) => query === query3 }), ).toEqual([query3]) expect(queryCache.findAll({ queryKey: ['posts'] })).toEqual([query4]) expect(queryCache.findAll({ fetchStatus: 'idle' })).toEqual([ query1, query2, query3, query4, ]) expect( queryCache.findAll({ queryKey: key2, fetchStatus: undefined }), ).toEqual([query2]) const promise = queryClient.prefetchQuery({ queryKey: keyFetching, queryFn: async () => { await sleep(20) return 'dataFetching' }, }) expect(queryCache.findAll({ fetchStatus: 'fetching' })).toEqual([ queryCache.find({ queryKey: keyFetching }), ]) await promise expect(queryCache.findAll({ fetchStatus: 'fetching' })).toEqual([]) }) test('should return all the queries when no filters are defined', async () => { const key1 = queryKey() const key2 = queryKey() await queryClient.prefetchQuery({ queryKey: key1, queryFn: () => 'data1', }) await queryClient.prefetchQuery({ queryKey: key2, queryFn: () => 'data2', }) expect(queryCache.findAll().length).toBe(2) }) }) describe('QueryCacheConfig error callbacks', () => { test('should call onError and onSettled when a query errors', async () => { const key = queryKey() const onSuccess = vi.fn() const onSettled = vi.fn() const onError = vi.fn() const testCache = new QueryCache({ onSuccess, onError, onSettled }) const testClient = createQueryClient({ queryCache: testCache }) await testClient.prefetchQuery({ queryKey: key, queryFn: () => Promise.reject<unknown>('error'), }) const query = testCache.find({ queryKey: key }) expect(onError).toHaveBeenCalledWith('error', query) expect(onError).toHaveBeenCalledTimes(1) expect(onSuccess).not.toHaveBeenCalled() expect(onSettled).toHaveBeenCalledTimes(1) expect(onSettled).toHaveBeenCalledWith(undefined, 'error', query) }) }) describe('QueryCacheConfig success callbacks', () => { test('should call onSuccess and onSettled when a query is successful', async () => { const key = queryKey() const onSuccess = vi.fn() const onSettled = vi.fn() const onError = vi.fn() const testCache = new QueryCache({ onSuccess, onError, onSettled }) const testClient = createQueryClient({ queryCache: testCache }) await testClient.prefetchQuery({ queryKey: key, queryFn: () => Promise.resolve({ data: 5 }), }) const query = testCache.find({ queryKey: key }) expect(onSuccess).toHaveBeenCalledWith({ data: 5 }, query) expect(onSuccess).toHaveBeenCalledTimes(1) expect(onError).not.toHaveBeenCalled() expect(onSettled).toHaveBeenCalledTimes(1) expect(onSettled).toHaveBeenCalledWith({ data: 5 }, null, query) }) }) describe('QueryCache.add', () => { test('should not try to add a query already added to the cache', async () => { const key = queryKey() await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data1' }) const query = queryCache.findAll()[0]! const queryClone = Object.assign({}, query) queryCache.add(queryClone) expect(queryCache.getAll().length).toEqual(1) }) }) })