From f91049835705872f7e48d2a39ad6365957fc6fc0 Mon Sep 17 00:00:00 2001 From: Gleb Bahmutov Date: Thu, 6 Oct 2022 10:27:54 -0400 Subject: [PATCH] fix: handle values null better (#39) --- README.md | 12 ++++++++++++ cypress/e2e/null.cy.js | 40 ++++++++++++++++++++++++++++++++++++++++ src/index.js | 10 +++++++++- 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 cypress/e2e/null.cy.js diff --git a/README.md b/README.md index 28ee709..f8ec183 100644 --- a/README.md +++ b/README.md @@ -185,6 +185,18 @@ cy See spec [alias.cy.js](./cypress/e2e/alias.cy.js) +## Null values + +Typically `null` values are treated same as `undefined` and follow the "else" path. You can specifically check for `null` and `not.null` using these assertions: + +```js +cy.wrap(null).if('null') // takes IF path +cy.wrap(null).if('not.null') // takes ELSE path +cy.wrap(42).if('not.null') // takes IF path +``` + +See spec [null.cy.js](./cypress/e2e/null.cy.js) + ## More examples Check out the spec files in [cypress/e2e](./cypress/e2e/) folder. If you still have a question, [open a GitHub issue](https://github.com/bahmutov/cypress-if/issues). diff --git a/cypress/e2e/null.cy.js b/cypress/e2e/null.cy.js new file mode 100644 index 0000000..cfd9e25 --- /dev/null +++ b/cypress/e2e/null.cy.js @@ -0,0 +1,40 @@ +/// +// @ts-check + +import '../../src' + +// https://github.com/bahmutov/cypress-if/issues/38 +describe('null value', () => { + it('handles null assertion', () => { + cy.wrap(null) + .if('null') + .log('null value') + .then(cy.spy().as('if')) + .else() + .then(cy.spy().as('else')) + cy.get('@if').should('have.been.called') + cy.get('@else').should('not.have.been.called') + }) + + it('handles not.null assertion', () => { + cy.wrap(null) + .if('not.null') + .log('null value') + .then(cy.spy().as('if')) + .else() + .then(cy.spy().as('else')) + cy.get('@else').should('have.been.called') + cy.get('@if').should('not.have.been.called') + }) + + it('handles 42 with not.null assertion', () => { + cy.wrap(42) + .if('not.null') + .log('null value') + .then(cy.spy().as('if')) + .else() + .then(cy.spy().as('else')) + cy.get('@if').should('have.been.called') + cy.get('@else').should('not.have.been.called') + }) +}) diff --git a/src/index.js b/src/index.js index e93ab89..dd69a67 100644 --- a/src/index.js +++ b/src/index.js @@ -68,7 +68,15 @@ Cypress.Commands.add( // set the subject and the assertions to take the IF branch hasSubject = Cypress._.get(cmd, 'attributes.prev.attributes.error') } else { - if (hasSubject && assertion) { + if (subject === null) { + if (assertion === 'null') { + hasSubject = true + assertionsPassed = true + } else if (assertion === 'not.null') { + hasSubject = true + assertionsPassed = false + } + } else if (hasSubject && assertion) { try { if (Cypress._.isFunction(assertion)) { const result = assertion(subject)