У меня есть 2 таблицы, producers
и contacts
. Чтобы добавить информацию в таблицу contacts
, я должен сначала добавить информацию в таблицу producers
. Это мой модульный тест:
'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()
})
})
Проблема в том, что когда таблица producers
создается при использовании функции addProducer
, она не сохраняется для функции addContacts
, чтобы использовать ее. Как мне это решить? Вот ответ от Jest Unit Test:
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' } ]
Как видите, он создает его, но только после того, как выдается ошибка ??
Вот код для таблицы производителей делается:
'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.')
}
}
А вот код составляемой таблицы контактов:
'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)
}