Skip to content

Snapshot testing #152

Description

@czosel

Currently, a typical test looks roughly like this:

  it("test coalesce operator", function() {
    var ast = parser.parseEval("$var = $a ?? true;");
    ast.children[0].right.kind.should.be.exactly("bin");
    ast.children[0].right.type.should.be.exactly("??");
    ast.children[0].right.left.kind.should.be.exactly("variable");
    ast.children[0].right.right.kind.should.be.exactly("boolean");
});

After working with snapshot-based testing for a while in prettier/plugin-php, I've really come to appreciate not having to write my own assertions anymore.

If we were to introduce snapshot-based testing here, the test case above would essentialy boil down to just one line, which could even be stored in a .php file:

$var = $a ?? true;

The testing framework would then generate the snapshot and save it in a file:

{
  "kind": "program",
  "children": [
    {
      "kind": "assign",
      "operator": "=",
      "left": {
        "kind": "variable",
        "name": "var",
        "byref": false,
        "curly": false
      },
      "right": {
        "kind": "bin",
        "type": "??",
        "left": {
          "kind": "variable",
          "name": "a",
          "byref": false,
          "curly": false
        },
        "right": {
          "kind": "boolean",
          "value": true,
          "raw": "true"
        }
      }
    }
  ],
  "errors": []
}

Like this, we'd see the exact AST changes that every PR introduces to any of the existing test cases.

It seems that Esprima is using a similar approach.

If you're interested, I could try preparing a little proof of concept - let me know what you think! 😄

Metadata

Metadata

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions