UUserWidgets require the following set up for them to work in tests and specs if you want to add them to a viewport in the test code.

//Widgets require a Game world to exist
UWorld* World = UWorld::CreateWorld(EWorldType::Game, false);
//Widgets require a UGameViewportClient, which needs to be set through
//a FWorldContext
FWorldContext& Context = GEngine->CreateNewWorldContext(EWorldType::Game);
Context.GameViewport = NewObject<UGameViewportClient>(GEngine);
//There must be a root overlay widget in the viewport
TSharedRef<SOverlay> Overlay = SNew(SOverlay);
Context.GameViewport->SetViewportOverlayWidget(nullptr, Overlay);
//We need a player controller to add the widget to the viewport
auto* PlayerController = World->SpawnActor<APlayerController>();
//We need a ULocalPlayer or the widget will refuse to work
auto* LP = NewObject<ULocalPlayer>(GEngine, GEngine->LocalPlayerClass);
//Create the widget as normal and it should work now
auto* Widget = CreateWidget(PlayerController, USomeUserWidget::StaticClass());