diff --git a/src/testdir/test_edit.vim b/src/testdir/test_edit.vim
index 70e6bea37..5bea988d4 100644
--- a/src/testdir/test_edit.vim
+++ b/src/testdir/test_edit.vim
@@ -1334,6 +1334,25 @@ func Test_edit_complete_very_long_name()
   set noswapfile
   let dirname = getcwd() . "/Xdir"
   let longdirname = dirname . repeat('/' . repeat('d', 255), 4)
+  if has('osx')
+    " The pathname truncation below might result in a valid pathname which is
+    " not a child of testdir/Xdir, and hence the test might create a directory
+    " at a wrong place.  Abort the test for safety if that's the case.
+    if strlen(dirname) >= 767
+      throw dirname . ' is too deep to execute the test'
+    endif
+    " On macOS, the system calls mkdir() and open() will fail with
+    " ENAMETOOLONG if the number of bytes of a whole pathname exceeds PATH_MAX
+    " (1024).  The number 766 is chosen so that strlen(longfilename) will be
+    " 1023.
+    let longdirname = longdirname[0:766]
+    if longdirname[765] == '/'
+      " When this is the case, the last path component of longfilename begins
+      " with '//', which can also cause an ENAMETOOLONG error when the file is
+      " made open even if the path length does not exceed PATH_MAX.
+      longdirname[765] = 'd'
+    endif
+  endif
   let longfilename = longdirname . '/' . repeat('a', 255)
   call mkdir(longdirname, 'p')
   call writefile(['Totum', 'Table'], longfilename)
