Why is undoManager of NSTextView subclass always nil when testing?
08:33 29 Apr 2026

I have a subclass (MyTextView) of NSTextView. When i try to test its (working) undo/redo using Swift Testing its undoManager property is always niland the test fails.

@MainActor
struct Undo {

    let mtv: MyTextView

    init() throws {
        mtv = MyTextView()
        mtv.insertText("Lorem ipsum dolor sit amet")
        mtv.moveToBeginningOfDocument(self)
        mtv.moveWordRightAndModifySelection(self)
    }
    
    @Test func roundtrip() async throws {
        #expect(mtv.selections == [(0, 5)])
        mtv.delete(self)
        #expect(mtv.selections == [(0, 0)])
        #expect(mtv.allowsUndo)
        mtv.undoManager?.undo() // undoManager is always nil
        #expect(mtv.selections == [(0, 5)])
        let strings = mtv.getSelectedText()
        #expect(strings == ["Lorem"])
    }
} 

Apparently the full machinery (run loop?) is not set up by the test. Is there some way force the instantiation of an undo manager during testing?

swift nstextview nsundomanager swift-testing