Browse Source

test(ui): Prevent components from being unmounted with context (#31716)

Scott Cooper 3 years ago
parent
commit
f1858324ff

+ 1 - 2
tests/js/sentry-test/reactTestingLibrary.tsx

@@ -33,9 +33,8 @@ function createProvider(contextDefs: Record<string, any>) {
 }
 
 function makeAllTheProviders({context, organization}: ProviderOptions) {
+  const ContextProvider = context ? createProvider(context) : Fragment;
   return function ({children}: {children?: React.ReactNode}) {
-    const ContextProvider = context ? createProvider(context) : Fragment;
-
     return (
       <ContextProvider>
         <CacheProvider value={cache}>

+ 33 - 0
tests/js/spec/reactTestingLibrary.spec.tsx

@@ -0,0 +1,33 @@
+import React, {useRef} from 'react';
+
+import {mountWithTheme, screen} from 'sentry-test/reactTestingLibrary';
+
+describe('rerender', () => {
+  // Taken from https://testing-library.com/docs/example-update-props/
+  let idCounter = 1;
+
+  const NumberDisplay = ({number}) => {
+    const id = useRef(idCounter++); // to ensure we don't remount a different instance
+
+    return (
+      <div>
+        <span data-test-id="number-display">{number}</span>
+        <span data-test-id="instance-id">{id.current}</span>
+      </div>
+    );
+  };
+
+  test('calling render with the same component on the same container does not remount', () => {
+    const {rerender} = mountWithTheme(<NumberDisplay number={1} />, {
+      // Passing a context caused rerender to re-mount if the wrapper is not setup correctly
+      context: TestStubs.routerContext(),
+    });
+    expect(screen.getByTestId('number-display')).toHaveTextContent('1');
+
+    // re-render the same component with different props
+    rerender(<NumberDisplay number={2} />);
+    expect(screen.getByTestId('number-display')).toHaveTextContent('2');
+
+    expect(screen.getByTestId('instance-id')).toHaveTextContent('1');
+  });
+});