How can I set Dark Mode in Swift UI Tests?

HI there,

I've been researching for a few days whether it's possible or not to programmatically activate Dark Mode within a Swift UI Test.

Environment:

  • Xcode 12.5.1

What I'm trying to achieve is: I'm using Fastlane to automate screenshots, so I would like to take one screenshot per device in dark mode. I know that Fastlane supports dark mode passing the dark_mode argument, but this will take all screenshots in dark mode. I'm looking for something like this:

    func testExample() throws {
        let app = XCUIApplication()
        setupSnapshot(app)  // Set up Fastlane snapshot
        app.launch()

        // Take first screenshot in light mode
        snapshot("1Launch")

        // Do something to enable dark mode

        // Take second screenshot in dark mode
        snapshot("1LaunchDarkMode")
  }

What I've tried so far:

    func testAppleInterfaceStyleDark() {
        let app = XCUIApplication()
        var launchArguments: [AnyHashable] = []

        launchArguments.append("-AppleInterfaceStyle")
        launchArguments.append("Dark")
        app.launchArguments = launchArguments as! [String]
        app.launch()
    }

As suggested in this Stackoverflow answer. But for me, It doesn't work.

While researching, I found lots of questions like mine but without answer. Like this one. What makes me wonder if it's impossible to do.

I would like to know if it's impossible to stop wasting time on this, or if it's possible, how can I solve it?

Thank you.

I have this question too

did you add the mentioned code (from the link) to SceneDelegate.swift? Also it would be slightly different for you, matching your own launchArgument.

How can I set Dark Mode in Swift UI Tests?
 
 
Q