Skip to content

Commit

Permalink
fix: handle values null better (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
bahmutov committed Oct 6, 2022
1 parent a6b1cf1 commit f910498
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 1 deletion.
12 changes: 12 additions & 0 deletions README.md
Expand Up @@ -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).
Expand Down
40 changes: 40 additions & 0 deletions cypress/e2e/null.cy.js
@@ -0,0 +1,40 @@
/// <reference types="cypress" />
// @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')
})
})
10 changes: 9 additions & 1 deletion src/index.js
Expand Up @@ -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)
Expand Down

0 comments on commit f910498

Please sign in to comment.