Mocha测试未能对相同对象的assert.equal

时间:2019-05-15 19:09:27

标签: javascript node.js mocha chai

我有一些Mocha测试未通过assert.equal,尽管看起来这两个项目是相同的。我可能不了解测试的运行方式,但是即使错误输出也显示了2个类似的东西:

states.js

const sqlite3 = require('sqlite3').verbose();
const util = require('util');

async function getDB() {
    return new Promise(function(resolve, reject) {
        let db = new sqlite3.Database('./project.db', (err) => {
          if (err) {
            console.error(err.message);
                reject(err)
          } else {
            console.log('Connected to the project database.');
                resolve(db)
        }
        });
        return db
    });
}

exports.getDB = getDB

try {
        // run these statements once to set up the db
        // let db = getDB();
        // db.run(`CREATE TABLE services(id INTEGER PRIMARY KEY, service text, date text)`);
        // db.run(`INSERT INTO services(id, service, date) VALUES (1, 'blah', '01-23-1987')`)
} catch(err) {
    console.log(err)
}

// is working
exports.get = async function(service) {
     function getResults(service) {
     return new Promise(async function (resolve, reject) {
                const db = await getDB();
                let sql = `SELECT Id id,
                               Service service,
                                                Date date
                        FROM services
                        WHERE service  = ?`;
                 db.get(sql, [service], (err, row) => {
                    if (err) {
                     console.error(err.message);
                     reject(err)
                 } else {
                     if (row) {
                         let this_row = {'id': row.id, 'service': row.service, 'date': row.date};
                         this_row ? console.log(row.id, row.service, row.date) : console.log(`No service found with the name ${service}`);
                         resolve(this_row)
                     } else {
                         resolve(null)
                     }
                 }
                })
     });
  }
    let row = await getResults(service)
    return row
}


let row = exports.get('blah')

console.log("Printing out what get returns:")
console.log(row)


exports.set = async function(service, state) {
    function setResults(service) {
        return new Promise(async function (resolve, reject) {
             const db = await getDB();
             let sql = `UPDATE services
                                set id = ?,
                                            service = ?,
                                            date = ?
                                 WHERE service  = ?`;
                try {
                    db.run(sql, [state.id, service, state.date, service]);
                    resolve();
                } catch(err) {
                    reject(err);
                }
    });
  }
    await setResults(service)
}

exports.set('blah', {'id': 1, 'date': '01-23-1987'})

exports.clear = async function(service) {
    function deleteResults(service) {
        return new Promise(async function (resolve, reject) {
             const db = await getDB();
             let sql = `DELETE from services
                                  WHERE service  = ?`;
                db.run(sql, [service]);
        });
    }
    await deleteResults(service)
}

tests.js

const mocha = require('mocha');

const assert = require('assert');
const expect = require('chai').expect;
const should = require('chai').should();

const state = require('../state');

let deletion_sql = `DELETE from services WHERE service  = ?`;

it("get() should return the expected row", async function() {
    let db = await state.getDB()
    await db.run(deletion_sql, 'blah')
    await db.run(`INSERT INTO services(id, service, date) VALUES (1, 'blah', '01-23-1987')`)
    let result = await state.get('blah')
    console.log("get test result is")
    console.log(result)
    assert.equal(result, { 'id': 1, 'service': 'blah', 'date': '01-23-1987' })
});


it("set() should set to new values as expected", async function() {
    let db = await state.getDB()
    await db.run(deletion_sql, 'blah')
    await db.run(`INSERT INTO services(id, service, date) VALUES (1, 'blah', '01-23-1987')`)
    await state.set('blah', {'id': 5, 'date': '05-22-2222'})
    let result = await state.get('blah')
    console.log("set test result is")
    console.log(result)
    assert.equal(result, { 'id': 5, 'service': 'blah', 'date': '05-22-2222' })
});

it("clear() should delete row from db", async function() {
  await state.clear('blah')
  let result = await state.get('blah')
  assert.equal(result, null)
})

输出如下:

get test result is
{ id: 1, service: 'blah', date: '01-23-1987' }
  1) get() should return the expected row
5 'blah' '05-22-2222'

set test result is
{ id: 5, service: 'blah', date: '05-22-2222' }
  2) set() should set to new values as expected

  3) clear() should delete row from db

  0 passing (2s)
  3 failing

  1) get() should return the expected row:

      AssertionError [ERR_ASSERTION]: { id: 1, service: 'blah', date: '01-23-1987' } == { id: 1, service: 'blah', date: '01-23-1987' }
      + expected - actual


      at Context.<anonymous> (src\tests\testStates.js:26:12)
      at process._tickCallback (internal/process/next_tick.js:68:7)

  2) set() should set to new values as expected:

      AssertionError [ERR_ASSERTION]: { id: 5, service: 'blah', date: '05-22-2222' } == { id: 5, service: 'blah', date: '05-22-2222' }
      + expected - actual

当项实际不同时,通常在错误下方显示带有+和-的diff,但此处的期望值和实际值均为空白,而==显示测试1和2的2个相同项。为什么会断言.equal测试对于相同项目失败?关于这些对象,肯定有一些我想念的东西。它们是否有所不同,因为它仍然将其表示为承诺而不是对象?我确实对两者都使用了await关键字。

1 个答案:

答案 0 :(得分:1)

我建议您在比较JavaScript对象时将断言更改为使用chai的deepEqual()。因此,您可以比较对象,以使它们具有相同的键和相同的值。

如果像在示例中一样使用equal()方法,则通过使用==比较实际对象和预期对象。通常,在比较JavaScript对象时,您不会对此感兴趣(除非您正在比较两个变量引用相同的对象,但是我建议您改为使用strictEqual())。