简体   繁体   English

如何使用 async-await 等待表创建/使其在 Jest 单元测试中持续存在?

[英]How to await table creation/make it persist in Jest Unit Test with async-await?

I have 2 tables, producers and contacts .我有 2 张桌子, producerscontacts To add information into the contacts table I must first add information to the producers table.要将信息添加到contacts表中,我必须首先将信息添加到producers表中。 This is my unit test:这是我的单元测试:

'use strict'

const Contacts = require('../modules/contacts.js')
const Producers = require('../modules/producers.js')


describe ('Add contact information()' , () => {

    test('Add contacts', async done => {
        expect.assertions(6)
        const producer = await new Producers()
        await producer.addProducer('James')
        const contact = await new Contacts()
        await contact.addContacts('James', 'www.johnwick.com', 'john@johnwick.com', '07724890765', '24, John Wick Street, London')
        const data = await contact.getAll()
        await expect (data.length).toBe(1)
        expect (data[0].ProducerID).toBe(1)
        expect (data[0].ProducerWebsite).toBe('www.johnwick.com')
        expect (data[0].ProducerEmail).toBe('john@johnwick.com')
        expect (data[0].ProducerNumber).toBe('07724890765')
        expect (data[0].ProducerAddress).toBe('24, John Wick Street, London')
        done()
    })

})

The problem is that when the producers table gets created when using the addProducer function it does not persist for the addContacts function to use it.问题是,当使用addProducer function 创建producers表时, addContacts function 无法使用它。 How do I solve that?我该如何解决? Here's the feedback from the Jest Unit Test:以下是来自 Jest 单元测试的反馈:

 FAIL  unit tests/contacts.spec.js
  Add contact information()
    × Add contacts (80ms)

  ● Add contact information() › Add contacts

    SQLITE_ERROR: no such table: producers



  console.log modules/producers.js:22
    Add Producer James

  console.log modules/producers.js:32
    Producer successfuly added.

  console.log modules/producers.js:67
    [ { ProducerID: 1, ProducerName: 'James' } ]

As you can see, it does create it, but only after the error is thrown??如您所见,它确实创建了它,但仅在引发错误之后才创建?

Here's the code for the producers table being made:这是正在制作的生产者表的代码:


'use strict'

const sqlite = require('sqlite-async')

module.exports = class Producers {


    //Create Database Table if it doesn't exist
    constructor(dbName = ':memory:') {
        return (async() => {
            this.db = await sqlite.open(dbName)
            const sql = 'CREATE TABLE IF NOT EXISTS producers(ProducerID INTEGER PRIMARY KEY UNIQUE, ProducerName TEXT NOT NULL UNIQUE)'
            await this.db.run(sql)
            return this
        })()
    }

    //Add function to add producers to database if not existing or add product types if producer exists. 
    async addProducer(name) {

        console.log('Add Producer', name)
        
        //Check if there are any Producers with the same name
        let sql = `SELECT * FROM producers WHERE ProducerName="${name}"`
        const data = await this.db.all(sql)
        
        //If producer doesn't exist add to database
        if(data.length === 0) {
            sql = `INSERT INTO producers (ProducerName) VALUES("${name}")`
            await this.db.run(sql)
            console.log('Producer successfuly added.')
        }
        
        //Else return error saying producer exists
        else {
            console.log('Producer already exists.')
            throw new Error ('Producer already exists.')
        }
    }

And here's the code for the contacts table being made:这是正在制作的联系人表的代码:


'use strict'

const sqlite = require('sqlite-async')

module.exports = class Contacts {


    //Create Database Table if it doesn't exist
    constructor(dbName = ':memory:') {
        return (async() => {
            this.db = await sqlite.open(dbName)
            const sql = 'CREATE TABLE IF NOT EXISTS contacts(ProducerID INTEGER, ProducerWebsite TEXT, ProducerEmail TEXT, ProducerNumber INTEGER, ProducerAddress TEXT)'
            await this.db.run(sql)
            return this
        })()
    }

    async addContacts (ProducerName, ProducerWebsite, ProducerEmail, ProducerNumber, ProducerAddress){
        // if(isNaN(Number.parseInt(ProducerNumber))) throw new Error('The Producer Number cannot contain letters')
        let sql = `INSERT INTO contacts (ProducerID, ProducerWebsite, ProducerEmail, ProducerNumber, ProducerAddress) VALUES (
            (SELECT ProducerID FROM producers WHERE ProducerName="${ProducerName}"), 
            "${ProducerWebsite}", "${ProducerEmail}", "${ProducerNumber}", "${ProducerAddress}")`
        await this.db.run(sql)
    }

I think each class is creating it's own in-memory database independent from the other.我认为每个 class 都在创建自己的独立于另一个的内存数据库。

According to https://www.sqlite.org/inmemorydb.html根据https://www.sqlite.org/inmemorydb.html

Every:memory: database is distinct from every other. Every:memory:数据库彼此不同。 So, opening two database connections each with the filename ":memory:" will create two independent in-memory databases.因此,打开两个数据库连接,每个连接文件名为“:memory:”,将创建两个独立的内存数据库。

So either create the DB at a single place and reuse the instance or use one of the methods in the link to share the in-memory database between the entities.因此,要么在一个地方创建数据库并重用实例,要么使用链接中的一种方法在实体之间共享内存数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM