如何模拟window.gapi.load()React + Jest

问题描述 投票:0回答:1

[Angular有一个问题可以回答,而Vuejs有一个没有任何答案的问题。我正在尝试寻找一种在测试中模拟window.gapi.load()函数的方法。我是React测试的新手,这是我到目前为止所拥有的:

it('should render the App component without crashing', function () {
  const component = renderer.create(
    shallow(
      <Root>
        <App/>
      </Root>
    )
  )

  let tree = component.toJSON()
  expect(tree).toMatchSnapshot()
})

我已经尝试了一个基本的beforeEach调用来尝试加载它或其他东西,但是那也不起作用。这是组件中的代码:

const App = () => {
  const { isSignedIn } = useSelector(state => state.auth)

  const renderApp = () => {
    if (isSignedIn) {
      return <Home/>
    } else {
      return (
          <div className='app'>
            <h1 id='logo'>netTube</h1>
            <GoogleAuth/>
          </div>
      )
    }
  }

  return (
      <>
        { renderApp() }
      </>
  )
}

以及GoogleAuth组件中的调用:

// GoogleAuth.jsx

componentDidMount() {
    window.gapi.load('client:auth2', () => {
      window.gapi.client.init({
        clientId: process.env.REACT_APP_GOOGLE_CLIENT_ID,
        scope: 'email'
      }).then(() => {
        this.auth = window.gapi.auth2.getAuthInstance()
        this.onAuthChange(this.auth.isSignedIn.get())
        this.auth.isSignedIn.listen(this.onAuthChange)
      })
    })
  }

[如果您还有其他要添加的内容,请询问。抱歉,如果没有足够的信息,就像我说的那样,我对React测试来说是新手。谢谢!

reactjs google-api jestjs enzyme gapi
1个回答
0
投票

您可以模拟组件使用的每个gapi调用。 (尽管使用浅渲染,但您的componentDidMount可能无法运行。)

类似:

window.gapi = {};
window.gapi.auth2.getAuthInstance = () => {isSignedIn : {get : () => true, listen : f => f()}};
window.gapi.client.init = (v) => true;
window.gapi.load = (a, f) => f();

作为it的第一行(甚至在每个func之前/之前更好)

© www.soinside.com 2019 - 2024. All rights reserved.