Skip to content

Operators

Chris Dibbern edited this page Jul 9, 2018 · 8 revisions

The fluent assertions API has several operators available to modify the current, fluent expression. They are listed alphabetically, below.

forReason

Adds metadata to a fluent string of assertions. Use where more fine-grained documentation is desired than can be provided by @Test("description strings").

Note: Not used much, now. Might be used for better statistics and error reporting, in the future.

forReason(reason: string, data?: any): IFluentCore<T, TNext, TPrev>

Example:

Assert(weirdThing)
  .forReason("My clarification of what intended behavior this assertion documents", { tags: ["critical"] } )
  .matches(/some regexp/)
  /* ... */;

lastContextualValue (property)

Unwraps the contextual value from the Expect framework, and returns it. Useful mainly for debugging.

let propVal = Assert({ prop: 3 }).has(p => p.prop).lastContextualValue;
// propVal now equals 3

kThx (property)

"K, thanks." :-) Ends a scope entered by the that operator. Think of it like a stack pop operation on the fluent scope. Hence, if you are three levels down when asserting over an object's properties, kThx.kThx.kThx would return you to the first level.

This operator, combined with the that operator, is intended to facilitate an alternative mode of expression from dictionary-style property assertions (see the hasProperties operators).

Assert({ a: { b: "c", d: "e" }, 5: { 16: 2, 17: 3}})
  .has(o => o.a).that
    .has(o => o.b).that.equals("c").kThx
    .has(o => o.d).that.equals("e").kThx
    .kThx
  .has(o => o[5]).that
    .has(o => o[16]).that.equals(2).kThx
    .has(o => o[17]).that.equals(3);

Is this operator completely necessary? You decide! K, thx. Bye!

maybe

Conditional not intended to facilitate parameterized testing (e.g., @TestCase).

Note: As with not, maybe only affects the next term. This is intentional since there is no concept of an explicitly-parenthetic expression, and tests could become confusing. It's better to keep your tests simple.

Assert(lambda).maybe(will).throws();

not (property)

Negates subsequent context, e.g., Assert(val).not.equals(3).

Note: Negation only applies to the next term. For example:

Assert(lambda)
  .not.throws(MyError)
    .that.has({ message: msg });

It might be tempting to believe the above assertion will pass as long as any errors thrown don't have a message equal to msg. However, .not.throws() will fail before .has() has a chance to execute. The proper way to write this is:

Assert(lambda)
  .throws(MyError)
  .not.has({ message: msg });

that (property)

Narrows the assertion scope to the last operation's implied result. Available only when narrowing the scope is possible/meaningful.

Assert({ prop: 3})
  .has(p => p.prop)
  .that.equals(3);   // valid assertion.
Assert({ prop: 3})
  .has(p => p.prop)
  .equals(3);        // will fail - speaks of original object, which does not equal 3.
Clone this wiki locally