Unit Test: Wait for entity state to change

Hello,

I’m trying to write a unit test that makes sure a sensor state updates correctly from one state to another.

How would I have pytest wait for the update coordinator or for the state to change before continuing with the test?

async def test_arrival_time(hass: HomeAssistant, monkeypatch: MonkeyPatch) -> None:
    """Tests arrival time is getting the correct value."""
    mock_now = datetime(2022, 12, 1, 2, 3, 4, 0, timezone.utc)
    monkeypatch.setattr(dt, "utcnow", lambda: mock_now)
    await setup_platform(hass, SENSOR_DOMAIN)
    
    old_state = hass.states.get("sensor.my_model_s_arrival_time")
    arrival_time = car_mock_data.VEHICLE_DATA["drive_state"]["active_route_minutes_to_arrival"]
    assert old_state.state == arrival_time

    car_mock_data.VEHICLE_DATA["drive_state"]["active_route_minutes_to_arrival"] -= 2 #Changing the arrival time

    #Need to wait here for state to be updated

    new_state = hass.states.get("sensor.my_model_s_arrival_time")
    new_arrival_time = car_mock_data.VEHICLE_DATA["drive_state"]["active_route_minutes_to_arrival"]
    assert new_state.state == new_arrival_time #Check if state changed to new arrival time

In the above code new_state would be the exact same as old_state. I’m expecting the new_state to be different but I believe the test runs too fast for the new_state to be updated.

If your code is time based you can freeze time and manually move it forward like this:

utcnow = dt_util.utcnow()
with freeze_time(utcnow):
  ... do things ...
  async_fire_time_changed(hass, utcnow + timedelta(seconds=300))
  ... expect things to have happened ...