|
| 1 | +import '@testing-library/jest-dom' |
| 2 | +import {defineComponent, h, computed} from 'vue' |
| 3 | +import {render} from '@testing-library/vue' |
| 4 | +import NumberDisplay from './components/NumberDisplay' |
| 5 | + |
| 6 | +// It'd probably be better if you test the component that's doing the rerendering |
| 7 | +// to ensure that the rerendered component is being updated correctly. |
| 8 | +// That said, if you'd prefer to, for example, update the props of a rendered |
| 9 | +// component, this function can be used to do so. |
| 10 | +test('calling rerender remounts the component and updates the props', () => { |
| 11 | + const {rerender, getByTestId} = render(NumberDisplay, { |
| 12 | + props: {number: 1}, |
| 13 | + }) |
| 14 | + |
| 15 | + expect(getByTestId('number-display')).toHaveTextContent('1') |
| 16 | + |
| 17 | + rerender({props: {number: 3}}) |
| 18 | + expect(getByTestId('number-display')).toHaveTextContent('3') |
| 19 | + |
| 20 | + rerender({props: {number: 5}}) |
| 21 | + expect(getByTestId('number-display')).toHaveTextContent('5') |
| 22 | + |
| 23 | + // Assert that, after rerendering and updating props, the component has been remounted, |
| 24 | + // meaning we are testing a different component instance than we rendered initially. |
| 25 | + expect(getByTestId('instance-id')).toHaveTextContent('3') |
| 26 | +}) |
| 27 | + |
| 28 | +test('rerender works with composition API', () => { |
| 29 | + const Component = defineComponent({ |
| 30 | + props: { |
| 31 | + foo: {type: String, default: 'foo'}, |
| 32 | + }, |
| 33 | + setup(props) { |
| 34 | + const foobar = computed(() => `${props.foo}-bar`) |
| 35 | + return () => |
| 36 | + h( |
| 37 | + 'div', |
| 38 | + {'data-testid': 'node'}, |
| 39 | + `Foo is: ${props.foo}. Foobar is: ${foobar.value}`, |
| 40 | + ) |
| 41 | + }, |
| 42 | + }) |
| 43 | + |
| 44 | + const {rerender, getByTestId} = render(Component) |
| 45 | + |
| 46 | + const originalNode = getByTestId('node') |
| 47 | + expect(originalNode).toHaveTextContent('Foo is: foo. Foobar is: foo-bar') |
| 48 | + |
| 49 | + rerender({props: {foo: 'qux'}}) |
| 50 | + |
| 51 | + const newNode = getByTestId('node') |
| 52 | + expect(newNode).toHaveTextContent('Foo is: qux. Foobar is: qux-bar') |
| 53 | +}) |
0 commit comments