简体   繁体   中英

Unit Testing Links With Only Jest

I was wondering if there was a way to unit test links with jest alone to make sure they go to the correct place. All other resources I have looked up have used enzyme or additional applications.

For example: Ensuring <Link to '/homepage> or <NavLink to '/homepage'> actually goes to the homepage.

Any additional resources to read would also be helpful and appreciated.

You can test the Link component with jestjs, react-dom , and history packages. We spy on the history.push() method before user click the Link , the Link component will call history.push() underly when user click it.

Eg

index.tsx :

import React from 'react';
import { Link } from 'react-router-dom';

export function About() {
  return <Link to="/home">home</Link>;
}

index.test.tsx :

import React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { act, Simulate } from 'react-dom/test-utils';
import { Router } from 'react-router-dom';
import { createMemoryHistory } from 'history';
import { About } from './';

describe('70535778', () => {
  let container: HTMLDivElement | null = null;
  let memoryHistory, pushSpy, replaceSpy;
  beforeEach(() => {
    container = document.createElement('div');
    document.body.appendChild(container);
    memoryHistory = createMemoryHistory();
    pushSpy = jest.spyOn(memoryHistory, 'push');
    replaceSpy = jest.spyOn(memoryHistory, 'push');
  });

  afterEach(() => {
    unmountComponentAtNode(container!);
    container!.remove();
    container = null;
    pushSpy.mockRestore();
    replaceSpy.mockRestore();
  });

  test('should pass', () => {
    act(() => {
      render(
        <Router history={memoryHistory}>
          <About />
        </Router>,
        container
      );
    });
    const a = container!.querySelector('a')!;
    Simulate.click(a, { defaultPrevented: false, button: 0 });
    expect(pushSpy).toBeCalledWith('/home');
  });
});

Test result:

 PASS  examples/70535778/index.test.tsx (12.11 s)
  70535778
    ✓ should pass (31 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.tsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        14.443 s
Ran all test suites related to changed files.

package versions:

"react": "^16.14.0",
"react-dom": "^16.14.0",
"react-router-dom": "^5.2.0",

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM