diff --git a/app/commands/spies-stubs-clocks.html b/app/commands/spies-stubs-clocks.html index f5e649865..58f1a0993 100644 --- a/app/commands/spies-stubs-clocks.html +++ b/app/commands/spies-stubs-clocks.html @@ -169,6 +169,99 @@
See all possible matchers at Sinonjs.org
+const greeter = {
+ /**
+ * Greets a person
+ * @param {string} name
+ */
+ greet (name) {
+ return `Hello, ${name}!`
+ },
+}
+
+cy.stub(greeter, 'greet')
+ .callThrough() // if you want non-matched calls to call the real method
+ .withArgs(Cypress.sinon.match.string).returns('Hi')
+ .withArgs(Cypress.sinon.match.number).throws(new Error('Invalid name'))
+
+expect(greeter.greet('World')).to.equal('Hi')
+expect(() => greeter.greet(42)).to.throw('Invalid name')
+expect(greeter.greet).to.have.been.calledTwice
+
+// non-matched calls goes the actual method
+expect(greeter.greet()).to.equal('Hello, undefined!')
+ See all possible matchers at Sinonjs.org
+const calculator = {
+ /**
+ * returns the sum of two arguments
+ * @param a {number}
+ * @param b {number}
+ */
+ add (a, b) {
+ return a + b
+ },
+}
+
+const spy = cy.spy(calculator, 'add').as('add')
+
+expect(calculator.add(2, 3)).to.equal(5)
+
+// if we want to assert the exact values used during the call
+expect(spy).to.be.calledWith(2, 3)
+
+// let's confirm "add" method was called with two numbers
+expect(spy).to.be.calledWith(Cypress.sinon.match.number, Cypress.sinon.match.number)
+
+// alternatively, provide the value to match
+expect(spy).to.be.calledWith(Cypress.sinon.match(2), Cypress.sinon.match(3))
+
+// match any value
+expect(spy).to.be.calledWith(Cypress.sinon.match.any, 3)
+
+// match any value from a list
+expect(spy).to.be.calledWith(Cypress.sinon.match.in([1, 2, 3]), 3)
+
+// expect the value to pass a custom predicate function
+// the second argument to "sinon.match(predicate, message)" is
+// shown if the predicate does not pass and assertion fails
+const isEven = (x) => x % 2 === 0
+
+expect(spy).to.be.calledWith(Cypress.sinon.match(isEven, 'isEven'), 3)
+
+// you can combine several matchers using "and", "or"
+const isGreaterThan = (limit) => (x) => x > limit
+const isLessThan = (limit) => (x) => x < limit
+
+expect(spy).to.be.calledWith(
+ Cypress.sinon.match.number,
+ Cypress.sinon.match(
+ isGreaterThan(2), '> 2').and(Cypress.sinon.match(isLessThan(4), '< 4'))
+)
+
+expect(spy).to.be.calledWith(
+ Cypress.sinon.match.number,
+ Cypress.sinon.match(isGreaterThan(200), '> 200').or(Cypress.sinon.match(3))
+)
+
+// matchers can be used from BDD assertions
+cy.get('@add').should('have.been.calledWith',
+ Cypress.sinon.match.number, Cypress.sinon.match(3)
+)
+
+// you can alias matchers for shorter test code
+const { match: M } = Cypress.sinon
+
+cy.get('@add').should('have.been.calledWith', M.number, M(3))