Search code examples
visual-studio-codevscode-snippets

In VS Code, what's an easy way of converting plain text test names into code?


I'm not sure if there's a proper word for this. I want to be able to write a list of tests in plain text, then convert them into a list of empty test functions.

For example, if I write

a user can view all documents

documents can be created

documents can edited

I would like to then be able to do something, like highlight the lines and run an extension, which would transform those lines into

/** @test */
public function a_user_can_view_all_documents()
{
    $this->markTestIncomplete('This test has not been implemented yet.');
}

/** @test */
public function documents_can_be_created()
{
    $this->markTestIncomplete('This test has not been implemented yet.');
}

/** @test */
public function documents_can_edited()
{
    $this->markTestIncomplete('This test has not been implemented yet.');
}

I currently use snippets to generate the test code without a function name. But I still have to do this for each test, AND type out the test names, which is a bit annoying since they're in snake_case.

Is there a built-in feature of VS Code that can do this?


Solution

  • You can create a snippet like this:

    "Create a test": {
        "prefix": "t2",
        "body": [
            "/** @test */",
            "public function ${TM_SELECTED_TEXT/\\s/_/g}()",
            "{",
            "\t$this-markTextIncomplete('This test has not been implemented yet.')",
            "}",
            
        ],
        "description": ""
    }
    

    and then either trigger it from that prefix - after selecting each line - or to simplify create a keybinding which will select the line for you and also insert the snippet. Use this keybinding (in your keybindings.json file):

    {
      "key": "alt+c",           // whatever you want
      "command": "runCommands",
      "args": {
        "commands": [
          "cursorHomeSelect",   // place cursor at end of each line first
          {
            "command": "editor.action.insertSnippet",
            "args": {
              "name": "Create a test",
            }
          },
        ]
      },
    }
    

    Insert a snippet creating test code


    Now if you really want to make one big selection of all the lines and trigger it just once that is going to be harder. Might be possible with an extension that examines the selection and ignores the empty lines.