如何使用计时器为 useEffect 编写 JEST 测试?

时间:2021-05-26 21:05:30

标签: react-native jestjs

我正在使用 void *thread_1(void *arg) { int value = *((int *)arg); cout<<"Value in thread: "<<value<<endl; int new_val = 345; pthread_exit(&new_val ); } int main(int argc, char* argv[]) { int *temp=15; void *return_val; pthread_t t1; pthread_create(&t1, NULL,thread_1,(void *)temp); pthread_join(t1,&return_val); cout<<"Value in main: "<<*temp<<endl; cout<<"Value from loop: "<<*(int*)return_val<<endl; } 检测应用连接状态并在连接丢失时显示一条消息。我如何为 useEffect 中的以下代码编写测试以确保消息显示/隐藏并且清理工作?

@react-native-community/netinfo

我尝试过类似的方法来检查应用程序是否已连接

  const { isConnected } = useContext(ConnectionContext); 
  ...
  useEffect(() => {
    const snack = setTimeout(() => {
      if (!isConnected) {
        showMessage({
          autoHide: false,
          message: 'Please try again later',
        });
      }
    }, 10000);
    const hideSnack = setTimeout(() => {
      if (isConnected) hideMessage();
    }, 5000);

    return () => {
      clearTimeout(snack);
      clearTimeout(hideSnack);
    };
  }, [isConnected]);

1 个答案:

答案 0 :(得分:0)

你可以使用jest fake timers来控制时间:

在顶部使用

jest.useFakeTimers();

然后当您需要将时间提前一定数量时使用:

jest.advanceTimersByTime(100);