Mock4JS: Constraints
Method Constraints
These are the constraints you can use with expects(). For example:
mockObject.expects(once()).someMethod()
- once()
the method must be invoked exactly once.
- atLeastOnce()
the method must be invoked at least once.
- exactly(n)
the method must be invoked exactly n times.
- never()
the method must not be invoked.
Argument Constraints
These are the constraints you can use with method arguments. For example:
mockObject.expects(once()).someMethod(eq("arg1"), ANYTHING, stringContains("hello"))
- eq(x)
the argument must equal x. The equals analysed by Javascript == except when the argument is an array, in which case each of the array elements must be ==
- stringContains(x)
the argument must be a string and must contain the substring x
- not(x)
the argument must not equal x. X can be a value or another argument constraint, eg,
mockObject.expects(once()).someMethod(not(stringContains("shrubbery")))
- and()
the argument must conform to all the specified constraints. eg,
mockObject.expects(once()).someMethod(and(stringContains("hello"), stringContains("world")))
- or()
the argument must conform to any one of the specified constraints. eg,
mockObject.expects(once()).someMethod(or(stringContains("hello"), stringContains("world")))
- ANYTHING
any argument value
- NOT_NULL
any argument value except null
- NOT_UNDEFINED
any argument value except undefined
Method Actions
These are the behaviours that a mock can exhibit when an expected method is invoked. For example:
mockObject.expects(once()).someMethod().will(returnValue("someResult"))
- returnValue()
- throwException(new Error(...))
Note that you can specify a list of actions. This allows you to change the behaviour of the mocked method on consequtive calls. For example:
mockObject.expects(exactly(3)).someMethod().will(returnValue("result1"), returnValue("result2"), throwException(new Error("problemo!")))