使用nodejs应用程序上使用sqlite3进行测试失败



我尝试测试数据库查询,我正在使用Objection这样的ORM和knex

项目应用程序的结构:

/project-sqlite
  /__tests__
    routes.test.js
  /models
    user.js
  /node_modules
  -app.js
  -package-lock.json
  -package.json
  -user.db

型号/用户.js:

const objection = require('objection');
const Model = objection.Model;
const Knex = require('knex');
const knex = Knex({
  client: 'sqlite3',
  useNullAsDefault: true,
  connection: {
    filename: './user.db'
  }
});
Model.knex(knex);
// Create database schema. You should use knex migration files to do this. We
// create it here for simplicity.
const schemaPromise = knex.schema.createTableIfNotExists('user', table => {
  table.increments('id').primary();
  table.string('name');
});
class User extends Model {
  static get tableName() {
    return 'user';
  }
  static get jsonSchema() {
    return {
      type: 'object',
      required: ['name'],
      properties: {
        id: { type: 'integer' },
        name: { type: 'string', minLength: 1, maxLength: 255 }
      }
    };
  }
};
schemaPromise.then(() => {
  return User.query().insert({name: 'User 1'});
}).then(user => {
  console.log('created: ', user.name, 'id: ', user.id);
});
module.exports = User;

app.js:

const express = require('express');
const User = require('./models/user');
app = express();
app.get('/users', (req, res) => {
  const newUser = {
    name: 'user 4050'
  };
  User
  .query()
  .insert(newUser)
  .then(user => {
    res.writeHead(200, {'Content-type': 'text/json'});
    res.end(JSON.stringify(user));
  })
})
app.get('/users1', (req, res) => {
  User
  .query()
  .then(user => {
    res.writeHead(200, {'Content-type': 'text/json'});
    res.end(JSON.stringify(user));
  })
})
app.listen(3000, ()=> {
  console.log('server runs on localhost:3000');
});

tests /routes.test.js:

const user = require('../models/user');
describe('Test model User', () => {
  test('should return User 1', (done) => {
    user
    .query()
    .where('id', 1)
    .then(userFounded => {
       expect(userFounded.name).toEqual('User 1');
       done();
    })
  });
});

测试失败了,但是我插入了一些用户,我得到了此错误:

Test model User
✕ should return User 1 (29ms)
  ● Test model User › should return User 1
    expect(received).toEqual(expected)
    Expected value to equal:
      "User 1"
    Received:
      undefined
    Difference:
      Comparing two different types of values. Expected string but received undefined.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sqlite@1.0.0 test: `jest`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the sqlite@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

我不明白有什么问题。这是由于与存储数据或尚未存储的文件没有连接的原因吗?

userFounded的类型是数组而不是对象,因此您无法使用userFounded.name使用用户的名称。

尝试:

expect(userFounde[0].name).toEqual('User 1')

最新更新