React-Native 使用 Jest 测试 AppState

Han*_*ans 6 event-listener react-native

如何触发AppState监听器来检查它是否正常工作?

AppState.addEventListener('change', (nextAppState) =>  { console.log('test')});
Run Code Online (Sandbox Code Playgroud)

Jest 有没有办法触发这个监听器?

use*_*564 6

我不太明白第一个解决方案是如何工作的,我尝试过但无法让它工作,但有一种不同的方法。

首先澄清一下,您试图调用代码中调用的 AppState.addEventListener('change', functionToInvokeOnChange) 的第二个参数的函数。幸运的是,Jest 为我们在 AppState.addEventListener(...) 上调用的任何参数提供了 jest.spyOn 方法。如果第二个参数是一个函数,那么您没有理由不能在 jest 环境中调用它。

说你有,

useEffect(() => {
    AppState.addEventListener('change', _handlerFunction);

    /* ... */
}, []);

const _handlerFunction = async (nextAppState) => { /* ...*/ }
Run Code Online (Sandbox Code Playgroud)

你可以这样测试:

it('... on state change', async () => {
   const appStateSpy = jest.spyOn(AppState, 'addEventListener');
   rendered = render(<Component />);
   await appStateSpy.mock.calls[0][1]('active');
   //assert this or that happens ect.
});
Run Code Online (Sandbox Code Playgroud)