【问题标题】:Jest test function returning a function which is having window.location.hrefJest 测试函数返回一个具有 window.location.href 的函数
【发布时间】:2021-12-13 08:38:34
【问题描述】:

如何为以下函数编写测试用例? 预期是:如果提供了 successPath,则 onSignInSuccess 应将其重定向到 successPath

export const onSignInSuccess = ( data ) => {
 return ( ) => {
  global.location.href = data?.detail?.data?.successPath;
 }
}

到目前为止我尝试过但它不起作用

  const data = { detail : { data: { redirectPage: true, successPath: 'test.com' } } }
  onSignInSuccess( data )()
  expect( jest.fn() ).toHaveBeenCalledWith( 'test.com' )

【问题讨论】:

  • expect( jest.fn() ).toHaveBeenCalledWith( 'test.com' ) - 期待我刚刚创建的这个模拟函数以某种方式已经被调用?无论如何,被测代码都没有调用任何东西,这个断言没有任何意义。
  • 对不起@jonrsharpe 我没有得到你,但我更新了问题。

标签: javascript function jestjs


【解决方案1】:

我通过嘲笑window.location.href找到了解决方案

it( 'should redirect to successPath if given', ()=>{
  global.window = Object.create( window );
  const url = 'http://test.com';
  Object.defineProperty( window, 'location', {
    value: {
      href: url
    }
  } );
  const data = { detail : { data: { redirectPage: true, successPath: 'test.com' } } }
  onSignInSuccess( data )()
  expect( global.location.href ).toBe( 'test.com' )
} );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 2021-08-08
    • 2019-09-21
    • 2018-03-24
    • 2021-07-23
    • 2019-06-26
    • 2019-03-13
    相关资源
    最近更新 更多