Search code examples
neo4jcyphercypress

Best way to run cypher queries on a neo4j database from cypress


I'm trying to run cypher queries against a neo4j database from cypress tests. I'm wondering what the best way to do this is. Is using cy.task() recommended for this? It would be helpful to see an implementation of this.

I've tried running a basic query using the below but this doesn't seem like the right way for cypress even though the queries do execute:

function runCypher(query) {
  const driver = neo4j.driver(Cypress.env('NEO4J_QA'), neo4j.auth.basic(Cypress.env('NEO4J_USER'), Cypress.env('NEO4J_PASSWORD')));
  const session = driver.session();
  session.run(query);
}

Solution

  • Looking at the notes for neo4j-driver, the example at Consuming Records with Promise API seem useful.

    // the Promise way, where the complete result is collected before we act on it:
    session
      .run('MERGE (james:Person {name : $nameParam}) RETURN james.name AS name', {
        nameParam: 'James'
      })                              // this is where your example gets to
      .then(result => {
        result.records.forEach(record => {
          console.log(record.get('name'))
        })
      })
      .catch(error => {
        console.log(error)
      })
      .then(() => session.close())
    

    So your function would just need to return the session call and access the results via a .then() callback.

    function runCypher(query) { 
      const {NEO4J_QA: url, NEO4J_USER: user, NEO4J_PASSWORD: password} = Cypress.env();
      const driver = neo4j.driver(url, neo4j.auth.basic(user, password)); 
      const session = driver.session(); 
      return session.run(query); 
    }
    
    it('tests neo4j query', () => {
      const myQuery = '...'
      runCypher(myQuery).then(results => {
        expect(results.records.length).to.eq(42)   // assertions here
      })
      .catch(error => {
        throw error                                // re-throw to fail the test
      })
      .then(() => session.close())                 // presume this is required for cleanup
    })
    

    You can use it in the browser, so I don't think you need a task.