Skip to content

Add support for aliases #171

@gavv

Description

@gavv

httpexpect is able to print assertion chain path on failure. For example, when you write:

e.GET("/endpoint").
  Expect().
  JSON().Object().Value("foo").
  Array().Element(0).Number()

and assertion fails, you will see:

        expected: value is number
        
        assertion:
          Request("GET").Expect().JSON().Object().Value("foo").Array().
            Element(0).Number()

Often it is convenient to create variables when making assertions:

foo := e.GET("/endpoint").
  Expect().
  JSON().Object().Value("foo").Array()

foo.Element(0).Number()
foo.Element(1).Number()
...

In this case, it would be nice if variables names were reflected in the failure message.

This issue suggest to implement support for aliases, which will work like this:

foo := e.GET("/endpoint").
  Expect().
  JSON().Object().Value("foo").Array().Alias("foo")

foo.Element(0).Number()
        expected: value is number
        
        assertion:
          foo.Element(0).Number()

To make it possible, the following changes are needed:

  • Add AssertionContext.AliasedPath. It will be similar to AssertionContext.Path, but will take into account aliases.
  • chain.enter() and chain.leave() should update both Path and AliasedPath
  • chain.clone() should clone both Path and AliasedPath
  • chain will provide new setAlias(name) method that will replace AliasedPath with a new slice with single element name, and keep Path untouched
  • To every inspector struct (Array, Object, Number, etc), add Alias() method that accepts a string name and returns receiver; it will just call chain.setAlias.

After this changes, AssertionContext.AliasedPath will automatically contain the value we're interested in. Now we just need to update DefaultFormatter:

  • add DisableAliases flag (zero by default), which disables new feature (enabled by default)
  • if aliases are enabled, fill FormatData.AssertPath using AliasedPath instead of Path

And that's it.

We also need to add unit tests:

  • comprehensive tests for alias support in chain
  • short unit test (or maybe new assertion in existing test) for every inspector object (Array, Object, etc)
  • e2e test for aliases in reports (see Add end-to-end tests for report formatting #165)

Finally we should add documentation:

  • added public methods should be documented
  • we should add a section to README that explains the feature

Metadata

Metadata

Assignees

Labels

featureNew feature or requesthelp wantedContributions are welcome

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions