<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Guillaume Brioudes on Medium]]></title>
        <description><![CDATA[Stories by Guillaume Brioudes on Medium]]></description>
        <link>https://medium.com/@guillaume-brioudes?source=rss-87e44275bac7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Guillaume Brioudes on Medium</title>
            <link>https://medium.com/@guillaume-brioudes?source=rss-87e44275bac7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 19:05:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guillaume-brioudes/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Visualizing Graphs in JavaScript with Graphology and ForceAtlas2]]></title>
            <link>https://medium.com/@guillaume-brioudes/visualizing-graphs-in-javascript-with-graphology-and-forceatlas2-11e257c394e0?source=rss-87e44275bac7------2</link>
            <guid isPermaLink="false">https://medium.com/p/11e257c394e0</guid>
            <category><![CDATA[network-layout]]></category>
            <category><![CDATA[graphology]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Guillaume Brioudes]]></dc:creator>
            <pubDate>Fri, 13 Jun 2025 19:27:58 GMT</pubDate>
            <atom:updated>2025-06-13T19:29:09.217Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<blockquote>Build and render graph layouts in JavaScript using Graphology, ForceAtlas2, and scalable SVG output.</blockquote><h3><strong>Why Use Graphology?</strong></h3><p><a href="https://graphology.github.io/">Graphology</a> is a robust JavaScript library for creating and manipulating graph structures, compatible with <strong>both Node.js and the browser</strong>. It provides a unified, well-designed API for building, analyzing, transforming, and visualizing graphs.</p><p>Graph layout (i.e., positioning nodes in space) is a non-trivial task that typically requires specialized algorithms. Graphology integrates with several layout-focused libraries to solve this, such as:</p><ul><li><strong>graphology-layout</strong>: for basic layouts like circular or random;</li><li><strong>graphology-layout-forceatlas2</strong>: for Force Atlas 2 physical simulation;</li><li><strong>graphology-layout-noverlap</strong>: for overlap removal.</li></ul><h3><strong>A Simple Layout Pipeline</strong></h3><p>Here’s a three-step layout pipeline to make your graphs both readable and visually appealing:</p><ol><li><strong>Initialize node positions with a circular layout</strong>;</li><li><strong>Apply Force Atlas 2</strong> for natural force-directed positioning;</li><li><strong>Use Noverlap</strong> to push nodes apart and avoid overlaps.</li></ol><pre>import Graph from &quot;graphology&quot;;<br>import { circular } from &quot;graphology-layout&quot;;<br>import forceAtlas2 from &quot;graphology-layout-forceatlas2&quot;;<br>import noverlap from &quot;graphology-layout-noverlap&quot;;<br><br>type NodeType = { color: string; label: string; x: number; y: number };<br>type EdgeType = {};<br><br>const graph = new Graph&lt;NodeType, EdgeType&gt;();<br><br>[].forEach((node) =&gt; {<br>  graph.addNode(node.id, { color: &#39;#000&#39; });<br>});<br>[].forEach((edge) =&gt; {<br>  graph.addDirectedEdgeWithKey(edge.nodeSourceId, edge.nodeTargetId);<br>});<br><br>// Step 1: Circular layout<br>const positionsCircular = circular(graph, { scale: 250, center: 2 });<br><br>graph.updateEachNodeAttributes((node, attr) =&gt; {<br>  return {<br>    x: positionsCircular[node].x,<br>    y: positionsCircular[node].y,<br>  };<br>});<br><br>// Step 2: Force Atlas 2<br>const positionsAtlas = forceAtlas2(graph, {<br>  iterations: 50,<br>  settings: forceAtlas2.inferSettings(graph),<br>});<br><br>graph.updateEachNodeAttributes((node, attr) =&gt; {<br>  return {<br>    x: positionsAtlas[node].x,<br>    y: positionsAtlas[node].y,<br>  };<br>});<br><br>// Step 3: Overlap removal<br>const positionsNoverlap = noverlap(graph, {<br>  maxIterations: 50,<br>  settings: {<br>    ratio: 50,<br>  },<br>});<br><br>graph.updateEachNodeAttributes((node, attr) =&gt; {<br>  return {<br>    x: positionsNoverlap[node].x,<br>    y: positionsNoverlap[node].y,<br>  };<br>});</pre><h3><strong>Rendering with React and SVG</strong></h3><p>Once the nodes are laid out, you can display the graph using a &lt;svg&gt; component in React. You can also export the SVG using static templating tools like Liquid or Handlebars.</p><p>The viewbox is automatically computed to fit all nodes, even for large-scale graphs.</p><pre>interface GraphViewProps {<br>  graph: Graph&lt;NodeType, EdgeType&gt;;<br>}<br><br>export default function GraphView({ graph }: GraphViewProps) {<br>  const width = 800;<br>  const height = 800;<br>  const nodeSize = 20;<br>  const margin = 50;<br><br>  const viewBox = (() =&gt; {<br>    let minX = Infinity,<br>      minY = Infinity,<br>      maxX = -Infinity,<br>      maxY = -Infinity;<br><br>    graph.forEachNode((_, attrs) =&gt; {<br>      minX = Math.min(minX, attrs.x);<br>      minY = Math.min(minY, attrs.y);<br>      maxX = Math.max(maxX, attrs.x);<br>      maxY = Math.max(maxY, attrs.y);<br>    });<br><br>    minX -= margin;<br>    minY -= margin;<br>    maxX += margin;<br>    maxY += margin;<br><br>    return `${minX} ${minY} ${maxX - minX} ${maxY - minY}`;<br>  })();<br><br>  return (<br>    &lt;svg width={width} height={height} viewBox={viewBox}&gt;<br>      &lt;g&gt;<br>        {graph.mapEdges(<br>          (edge, attrs, source, target, sourceAttrs, targetAttrs) =&gt; (<br>            &lt;path<br>              key={edge}<br>              d={`M${sourceAttrs.x},${sourceAttrs.y} L${targetAttrs.x},${targetAttrs.y}`}<br>              stroke=&quot;#888&quot;<br>              strokeWidth={1}<br>              fill=&quot;none&quot;<br>            /&gt;<br>          )<br>        )}<br>      &lt;/g&gt;<br>      &lt;g&gt;<br>        {graph.mapNodes((node, attrs) =&gt; (<br>          &lt;circle<br>            key={node}<br>            cx={attrs.x}<br>            cy={attrs.y}<br>            r={nodeSize / 2}<br>            fill={attrs.color}<br>            strokeWidth={2}<br>          /&gt;<br>        ))}<br>      &lt;/g&gt;<br>    &lt;/svg&gt;<br>  );<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11e257c394e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Hybrid CLI and Web App with Node.js and Webpack]]></title>
            <link>https://medium.com/@guillaume-brioudes/building-hybrid-cli-web-app-with-node-js-and-webpack-551c433cc1bd?source=rss-87e44275bac7------2</link>
            <guid isPermaLink="false">https://medium.com/p/551c433cc1bd</guid>
            <category><![CDATA[nunjucks]]></category>
            <category><![CDATA[node-cli]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[esm]]></category>
            <dc:creator><![CDATA[Guillaume Brioudes]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 19:22:30 GMT</pubDate>
            <atom:updated>2025-04-12T19:22:30.126Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>I’m presenting a hybrid development environnement. <a href="https://cosma.arthurperret.fr/">Cosma</a> is a CLI Node.js app that generate files for web browsers. Frontend, backend code and assets are bundled <strong>into a single executable file</strong>.</p><p>We’ll use:</p><ul><li>Modern JavaScript (ES6+)</li><li>ESM module system</li><li>YAML files</li><li>Nunjucks templates</li><li>Image support (inline base 64)</li><li><em>Ready for a future migration to TypeScript</em></li><li>Webpack, twice: once for the web part, once for the CLI part</li></ul><p>To finally bundle one CommonJs executable file.</p><p>Check out the <a href="https://github.com/graphlab-fr/cosma">GitHub repo here</a> with full code.</p><p>Cosma is a CLI that can generate static web pages. These pages contain HTML, CSS, JS and images. It’s intended to be portable, easy to distribute, and — most importantly — self-contained.</p><h3><strong>Architecture</strong></h3><p><a href="https://webpack.js.org/concepts/">Webpack</a> makes it possible to bundle both the frontend and the backend logic into a single executable.</p><p>We use <strong>two Webpack configs</strong>:</p><ul><li>One to bundle the frontend into a raw JavaScript string.</li><li>One to package everything (including the frontend) into an executable CLI app.</li></ul><pre>                                      ────────────┐<br>                            static/icons/**       │<br>                    ───┐    static/template/**.njk│<br>    core/frontend/**.js├──► front.raw.js          │<br>───────────────────────┘                          │<br>webpack-front.config.mjs    core/i18n.yml         │<br>                            app.js                ├───► back.cjs<br>                            ──────────────────────┘<br>                            webpack-back.config.mjs</pre><p>The final output is back.cjs, a Node.js executable file with:</p><ul><li>No dependencies</li><li>No relative file paths</li><li>A fully bundled frontend, inline</li></ul><p>You can install and use it like this:</p><pre>npm install back.js<br>cosma --version</pre><h3><strong>Webpack Configurations</strong></h3><h4><strong>Frontend</strong></h4><p>We compile the frontend with <a href="https://babeljs.io/docs/">Babel</a> and Webpack. This ensures modern <a href="https://medium.com/sliit-foss/es5-vs-es6-in-javascript-cb10f5fd600c">syntax like ES6 works</a>, while still supporting all browsers.</p><p>The output file front.raw.js will later be imported as raw source code in the backend.</p><pre>export default {<br>  entry: path.resolve(__dirname, &quot;./core/frontend/index.js&quot;),<br>  output: {<br>    path: path.resolve(__dirname, &quot;./dist&quot;),<br>    filename: &quot;front.raw.js&quot;,<br>  },<br>  module: {<br>    rules: [<br>      {<br>        test: /\.m?js$/,<br>        exclude: /(node_modules)/,<br>        use: {<br>          loader: &quot;babel-loader&quot;,<br>          options: { presets: [&quot;@babel/preset-env&quot;] },<br>        },<br>      },<br>    ],<br>  },<br>  resolve: { extensions: [&quot;.js&quot;] },<br>};</pre><h4><strong>Backend</strong></h4><p>The backend Webpack config does more:</p><ul><li>It embeds the frontend bundle as raw source</li><li>It handles YAML, Nunjucks, images</li><li>It adds a proper <em>shebang</em> line to make the output directly executable</li></ul><pre>export default {<br>  entry: path.resolve(__dirname, &quot;./app.js&quot;),<br>  output: { path: path.resolve(__dirname, &quot;./dist&quot;), filename: &quot;back.cjs&quot; },<br>  target: &quot;node&quot;,<br>  module: {<br>    rules: [<br>      { test: /\.ya?ml$/, use: &quot;yaml-loader&quot; },<br>      { test: /\.njk$/, type: &quot;asset/source&quot; },<br>      { test: /\.raw.js$/, type: &quot;asset/source&quot; }, // frontend bundle as plain text<br>      { test: /\.svg$/, type: &quot;asset/source&quot; },<br>      { test: /\.png$/, type: &quot;asset/inline&quot; },<br>    ],<br>  },<br>  plugins: [<br>    // put executable head on top of bundle<br>    new webpack.BannerPlugin({ banner: &quot;#!/usr/bin/env node&quot;, raw: true }),<br>  ],<br>  resolve: {<br>    extensions: [&quot;.js&quot;],<br>    alias: {<br>      front: path.resolve(__dirname, &quot;./dist/front.raw.js&quot;),<br>    },<br>  },<br>};</pre><h3><strong>Development &amp; Testing</strong></h3><p>The package.json contains a set of scripts for building the executable, both for development and production.</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;prepare&quot;: &quot;npm run build:front &amp;&amp; npm run build:back&quot;,<br>    &quot;watch:front&quot;: &quot;./node_modules/.bin/webpack build --config ./webpack-front.config.mjs --mode development --watch&quot;,<br>    &quot;build:front&quot;: &quot;./node_modules/.bin/webpack build --config ./webpack-front.config.mjs --mode production&quot;,<br>    &quot;watch:back&quot;: &quot;./node_modules/.bin/webpack build --config ./webpack-back.config.mjs --mode development --watch&quot;,<br>    &quot;build:back&quot;: &quot;./node_modules/.bin/webpack build --config ./webpack-back.config.mjs --mode production&quot;<br>  }<br>}</pre><p>To test the application in CI, all you need is to install dependencies and build the executable. Then you can use its commands:</p><pre># install Cosma&#39;s dependencies and build the executable<br>npm install<br># install Cosma as a global CLI<br>npm install . --global<br># use cosma to generate .html files<br>cosma modelize</pre><p>You can integrate E2E testing with Cypress or Playwright to validate the generated HTML output.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=551c433cc1bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integration Testing with Apollo Client]]></title>
            <link>https://medium.com/@guillaume-brioudes/integration-testing-with-apollo-client-0056ff8d4c52?source=rss-87e44275bac7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0056ff8d4c52</guid>
            <category><![CDATA[apollo-client]]></category>
            <category><![CDATA[vitest]]></category>
            <category><![CDATA[graphql-testing]]></category>
            <category><![CDATA[msw]]></category>
            <category><![CDATA[mocking-graphql]]></category>
            <dc:creator><![CDATA[Guillaume Brioudes]]></dc:creator>
            <pubDate>Tue, 18 Feb 2025 19:06:04 GMT</pubDate>
            <atom:updated>2025-04-22T08:52:22.529Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>In the <a href="https://martinfowler.com/articles/practical-test-pyramid.html#TheTestPyramid">testing pyramid</a> of a web application, I have long overlooked integration tests. However, they are particularly effective at detecting regressions, often more so than end-to-end tests, thanks to their fast execution (fail fast) and ease of setup.</p><p>For integration tests with GraphQL, the data, even if mocked, should always be validated against the schema. There should be no need to mock request-sending systems, caching mechanisms, or data loading processes (Suspense).</p><h3>Technical Choices in This Implementation</h3><ul><li>I have largely based this implementation on the <a href="https://www.apollographql.com/docs/react/development-testing/schema-driven-testing#configuring-your-test-environment">tutorial provided by the Apollo team</a>, with some adjustments.</li><li>Using <a href="https://vitest.dev/"><strong>Vitest</strong></a><strong> </strong>as the testing framework eliminates the <a href="https://mswjs.io/docs/migrations/1.x-to-2.x#frequent-issues">need to fix the interface</a> between the Node.js environment and JSDom. A polyfill is required when using Jest.</li><li>The <a href="https://mswjs.io/"><strong>MSW</strong></a> tool allows intercepting GraphQL requests without directly mocking fetch and provides a highly intuitive and well-documented API.</li><li>The <strong>Suspense</strong> component in the test covers the useSuspenseQuery hook. The test verifies the fallback content and ensures that the expected content appears once the request is completed.</li></ul><pre>import { gql } from &quot;@apollo/client&quot;;<br>import { buildSchema, execute, ExecutionResult } from &quot;graphql&quot;;<br>import { ObjMap } from &quot;graphql/jsutils/ObjMap&quot;;<br>import { graphql, HttpResponse } from &quot;msw&quot;;<br>import {<br>  afterAll,<br>  afterEach,<br>  beforeAll,<br>  beforeEach,<br>  describe,<br>  test,<br>} from &quot;vitest&quot;;<br>import {<br>  ApolloClient,<br>  ApolloProvider,<br>  HttpLink,<br>  InMemoryCache,<br>} from &quot;@apollo/client&quot;;<br>import { render, screen } from &quot;@testing-library/react&quot;;<br>import { setupServer } from &quot;msw/node&quot;;<br><br>const schema = buildSchema(`<br>  type Query {<br>    me: User<br>  }<br><br>  type User {<br>    id: ID<br>    name: String<br>  }<br>`);<br><br>const handlers = [<br>  graphql.operation&lt;ExecutionResult&lt;ObjMap&lt;unknown&gt;, ObjMap&lt;unknown&gt;&gt;&gt;(<br>    async ({ query, variables, operationName }) =&gt; {<br>      const document = gql(query);<br><br>      const result = await execute({<br>        document,<br>        operationName,<br>        schema,<br>        variableValues: variables,<br>        rootValue: {<br>          me() {<br>            return {<br>              __typename: &quot;User&quot;,<br>              id: &quot;507f1f77bcf86cd799439011&quot;,<br>              name: &quot;John Doe&quot;,<br>            };<br>          },<br>        },<br>      });<br><br>      return HttpResponse.json(result);<br>    }<br>  ),<br>];<br><br>const httpLink = new HttpLink({<br>  uri: &quot;/graphql&quot;,<br>});<br><br>describe(&quot;test suite&quot;, () =&gt; {<br>  let client: ApolloClient&lt;NormalizedCacheObject&gt;;<br>  beforeEach(() =&gt; {<br>    client = new ApolloClient({<br>      cache: new InMemoryCache({<br>        // ...configuration options...<br>      }),<br>      link: httpLink,<br>    });<br><br>    // put query in cache<br>    client.writeQuery({<br>      query: QUERY,<br>      data: {},<br>    });<br>  });<br><br>  const server = setupServer(...handlers);<br><br>  beforeAll(() =&gt; server.listen({ onUnhandledRequest: &quot;error&quot; }));<br>  afterAll(() =&gt; server.close());<br>  afterEach(() =&gt; server.resetHandlers());<br><br>  test(&quot;renders without error, put in cache&quot;, async () =&gt; {<br>    const { container } = render(<br>      &lt;ApolloProvider client={client}&gt;<br>        &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>          &lt;div&gt;content&lt;/div&gt;<br>        &lt;/Suspense&gt;<br>      &lt;/ApolloProvider&gt;<br>    );<br><br>    await screen.findByText(&quot;Loading...&quot;);<br>    expect(await screen.queryByText(&quot;content&quot;)).toBeTruthy();<br><br>    expect(client.cache.extract()).toHaveProperty(&quot;507f1f77bcf86cd799439011&quot;, {<br>      id: &quot;507f1f77bcf86cd799439011&quot;,<br>      name: &quot;John Doe&quot;,<br>    });<br>  });<br>});</pre><p>Edited on 2025/04/02 to reset Apollo client and the cache before each test. This is essential to isolate tests. I add an assertion for Apollo cache.</p><p>Edited on 2025/04/22 to add an example of how to insert queries into the cache with client.writeQuery. <a href="https://www.apollographql.com/docs/react/data/queries#setting-a-fetch-policy">Depending on your cache policy</a>, Apollo may call this data without sending a dedicated query.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0056ff8d4c52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I write unit tests]]></title>
            <link>https://medium.com/@guillaume-brioudes/why-i-write-unit-tests-7712290b910f?source=rss-87e44275bac7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7712290b910f</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-documentation]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Guillaume Brioudes]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 20:17:19 GMT</pubDate>
            <atom:updated>2025-02-15T20:17:19.279Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>I use unit tests as <strong>sandboxes and specification lists</strong>. I don’t rely on them to detect bugs or regressions — I leave that role to integration or end-to-end tests.<br>Unit tests are precise, quick to write, and fast to execute. They are excellent tools for exploring the boundaries of a functional structure and quickly addressing doubts.</p><p>In French, we say, <em>“Tester c’est douter,”</em> as a joke about the lack of confidence every developer experiences as their software grows in complexity. Sometimes, even when everything works, I feel uncertain and need a quick way to verify the system’s state.</p><h3>Specification Lists</h3><p>I need to articulate why my methods exist and how they should be used by other developers. <strong>Tests serve as executable documentation</strong> — examples that explain intent. They are a form of analysis and simplification that any contributor can consult and expand upon.</p><blockquote>This is what happens when you order tea. Here’s what happens when you order five teas. And if you order nothing? Oh, wait — what should happen if you order coffee?</blockquote><p>Each answer can raises new questions.</p><h3>A Sandbox</h3><p>Often, I have doubts about a method or an interface. So, I formalize the case, set up a few test subjects, and run the execution. I get either a <em>fail fast</em> response or confirmation.<br>If the behavior is validated and relevant to others, I keep it as a new specification.<br>If it fails, it means my instinct was right — I might have just avoided a bug. The code needs to change, whether inside the method or elsewhere in the system.</p><p><strong>Unit tests are not designed to find bugs</strong>; they are meant to formalize usage.<br>If a unit test fails, it doesn’t indicate a bug — it highlights a case that wasn’t accounted for in the existing specifications. That case may be outdated or may need to be enforced.</p><h3>Conclusion</h3><p>Unit tests are tools for exploration, documentation, and formalization. They help me structure my thinking, refine my intent, and challenge my technical decisions. Each test is a conversation with my code — a way to validate an assumption or uncover a flaw.<br>It’s not the test itself that prevents bugs, but the doubts it raises and the discussions it sparks with my peers.</p><p>Testing is doubting — but it’s also understanding. And in the end, it’s that understanding that <strong>makes software more robust and development more confident</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7712290b910f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playwright’s Locator Confuses Elements Inside a React Fragment]]></title>
            <link>https://medium.com/@guillaume-brioudes/playwrights-locator-confuses-elements-inside-react-fragment-483595bb9b9e?source=rss-87e44275bac7------2</link>
            <guid isPermaLink="false">https://medium.com/p/483595bb9b9e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[e2e-testing]]></category>
            <category><![CDATA[playwrights]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Guillaume Brioudes]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 18:48:27 GMT</pubDate>
            <atom:updated>2025-03-10T18:23:04.120Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>When using Playwright to test a React component that contains a <a href="https://react.dev/reference/react/Fragment">fragment</a>, you may encounter an unexpected error. Consider the following example:<br>This component consists of a fragment containing two paragraphs with different content.</p><pre>function Content() {<br>  return (<br>    &lt;&gt;<br>      &lt;p data-testid=&quot;first&quot;&gt;foo&lt;/p&gt;<br>      &lt;p data-testid=&quot;second&quot;&gt;bar&lt;/p&gt;<br>    &lt;/&gt;<br>  )<br>}<br><br>await expect(container).toBeVisible();</pre><p>We want to test the component’s visibility using the Playwright end-to-end testing tool.<br>Playwright provides an <a href="https://playwright.dev/docs/other-locators#react-locator">experimental method for selecting React components</a>.</p><p>Below, we select the component and then test its visibility:</p><pre>const container = page.locator(&#39;_react=Content&#39;);<br>await expect(container).toBeVisible();</pre><p>Playwright will then throw an error, indicating that it cannot check the visibility of what it has detected as two elements. It provides distinguishing identifiers for each:</p><pre>Error: expect.toBeVisible: Error: strict mode violation: locator(&#39;_react=Content&#39;) resolved to 2 elements:<br>    1) &lt;div data-testid=&quot;first&quot;&gt;…&lt;/div&gt; aka getByTestId(&#39;first&#39;)<br>    2) &lt;div data-testid=&quot;second&quot;&gt;…&lt;/div&gt; aka getByTestId(&#39;second&#39;)</pre><p>This behavior occurs because the fragment does not create a unique parent, causing Playwright to <strong>detect multiple elements under the same locator</strong>.</p><h3>Conclusion</h3><p>To avoid this error, you have two options:</p><ul><li>Use a more other selector, such as getByTestId, to directly target the desired element.</li><li>Wrap the fragment in a &lt;div&gt; if it does not introduce development and UI constraints.</li></ul><p>This ensures Playwright can properly locate and test the component. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=483595bb9b9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validate and Submit a Form with React 19’s New API]]></title>
            <link>https://medium.com/@guillaume-brioudes/validate-submit-react-19-form-192f6609771d?source=rss-87e44275bac7------2</link>
            <guid isPermaLink="false">https://medium.com/p/192f6609771d</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[useactionstate]]></category>
            <category><![CDATA[html-form-validation]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[html5]]></category>
            <dc:creator><![CDATA[Guillaume Brioudes]]></dc:creator>
            <pubDate>Wed, 29 Jan 2025 19:25:25 GMT</pubDate>
            <atom:updated>2025-02-17T18:42:46.092Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>With <a href="https://react.dev/blog/2024/12/05/react-19#actions">React’s new API</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Constraint_validation">HTML5 form validation</a>, it’s quick and easy to set up robust form validation and submission.</p><p>In the code snippet below, we’ll create a form that <strong>behaves like a native browser form</strong> while adding modern enhancements:</p><ul><li>A button allows the form to be submitted either by clicking it or pressing the “Enter” key.</li><li>The “id” field is validated to ensure it’s not empty and contains exactly 5 digits; otherwise, an error will be displayed on submit.</li><li>Submitting the form doesn’t reload the page or reset its values.</li><li>The desired field values are efficiently selected using FormData.</li><li>Users are prevented from resubmitting the form while the asynchronous request is still in progress.</li><li>A success message is displayed to the user if the operation completes successfully.</li></ul><pre>function App() {<br>  const [output, formAction, isPending] = useActionState&lt;<br>    string | undefined,<br>    FormData<br>  &gt;(async (prev, formData) =&gt; {<br>    const data = {<br>      id: formData.get(&quot;id&quot;),<br>    };<br><br>    await mutation(data);<br><br>    return `You save id &quot;${data.id}&quot;`;<br>  }, undefined);<br><br>  const formRef = useRef&lt;HTMLFormElement&gt;(null);<br>  usePersistentForm(formRef);<br><br>  return (<br>    &lt;form action={formAction} ref={formRef}&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        name=&quot;id&quot;<br>        onChange={(e) =&gt; {<br>          e.target.setCustomValidity(&quot;&quot;);<br><br>          if (!/^\d{5}$/.test(e.target.value)) {<br>            e.target.setCustomValidity(&quot;Should contains 5 numbers.&quot;);<br>          }<br>        }}<br>        required<br>      /&gt;<br><br>      {output &amp;&amp; &lt;output&gt;{output}&lt;/output&gt;}<br><br>      &lt;button type=&quot;submit&quot; disabled={isPending}&gt;<br>        Send<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}<br><br>function usePersistentForm (ref: RefObject&lt;HTMLFormElement&gt;) {<br>  useEffect(() =&gt; {<br>    if (!ref.current) {<br>      throw new Error(&#39;Form ref is not defined.&#39;);<br>    }<br><br>    const form = ref.current;<br><br>    const handleReset = (e) =&gt; {<br>      e.preventDefault();<br>    };<br><br>    form.addEventListener(&#39;reset&#39;, handleReset);<br>    return () =&gt; {<br>      form.removeEventListener(&#39;reset&#39;, handleReset);<br>    };<br>  }, []);<br>};</pre><p>Edited on 2025/02/17 to create a reusable usePersistent hook.<br>I store ref.current on a variable to remove the event on unmount since ref.current is undefined on unmount.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=192f6609771d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>