【问题标题】:Create unit test with Jest and React testing library for helper which generate a domain url使用 Jest 和 React 测试库为生成域 url 的助手创建单元测试
【发布时间】:2022-02-19 00:21:29
【问题描述】:

我创建了一个辅助函数来生成一个带有 url 中域的 url:

const generateUrl = () => {
  if (typeof window !== 'undefined') {
    return window.location.href;
  }
  return null;
};

export default generateUrl;

我需要为此函数编写一个单元测试。我正在使用 Jest 和 React 测试库。

import { Location } from 'react-router-dom';

import generateUrl from './generate-url';

// function mock(pathname: string): Location {
//  return {
//    pathname,
//  };
// }

describe('generateUrl', () => {
  it('should display url with domain', () => {
    expect(
      generateUrl().toStrictEqual('http://localhost:3000/?id=e3f3ef3f');
  });

});

如何为这种情况编写测试?

【问题讨论】:

    标签: reactjs jestjs window react-router-dom react-testing-library


    【解决方案1】:

    您可以为单元测试模拟 window.location 对象。

    import generateUrl from './generate-url';
    
    describe('generateUrl', () => {
      it('should display url with domain', () => {
        // save a reference of the window object
        const windowCache = window;
    
        // update the location.href property
        window.location = {
          href: 'http://localhost:3000/?id=e3f3ef3f',
        };
    
        // test
        expect(generateUrl()).toStrictEqual('http://localhost:3000/?id=e3f3ef3f');
    
        // restore cached window reference
        window = windowCache;
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-03-24
      • 2020-06-14
      • 2020-06-01
      • 2021-09-20
      • 2019-11-20
      • 2019-04-22
      • 2022-01-06
      • 1970-01-01
      • 2021-06-07
      相关资源
      最近更新 更多