Answer the question
In order to leave comments, you need to log in
How to do a Unit test of a unit where there is an interaction with an external service?
Good afternoon.
How to make a Unit test of a unit where there is an interaction with an external service?
Used by NodeJS Code
example:
async SynchShopProds (task) {
return new Promise((resolve) => {
try {
fetch('example.url, {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': `Bearer ${task.accessToken}`,
'User-Agent': UserAgent
},
body: JSON.stringify({ "searchTerm":null, "offerStatus":null, "categoryCode":null, "cityId":null, "start":task.start, "count":100 }),
})
.then(res => res.json())
.then(json => {
console.log(json)
const r = json
if (r.errors) {
if (r.errors[0].type === 'InvalidTokenError') {
resolve({
status: false,
errorType: 'InvalidTokenError'
})
}
return
}
if (r.totalCount) {
if (r.offers != null) {
let insertProducts = ''
let countPlus = 0
r.offers.forEach(function callback(value, index, array) {
let name = value.masterProduct.name.replace(/\'/g, "''")
insertProducts += `INSERT INTO products ("kaspiSku", "kaspiLink", "name", "thumbnailUrl") VALUES ('${value.masterProduct.sku}', '${value.masterProduct.productUrl}', '${name}', '${value.masterProduct.primaryImage.small}') ON CONFLICT ("kaspiSku") DO NOTHING;`
countPlus++
})
console.log('COUNT PLUS', countPlus)
poolDB.connect((err, client, done) => {
const shouldAbort = err => {
if (err) {
console.error('Error in transaction', err.stack)
client.query('ROLLBACK', err => {
if (err) {
console.error('Error rolling back client', err.stack)
}
done()
})
resolve({
status: false,
errorType: 'DatabaseError'
})
}
return !!err
}
client.query('BEGIN', err => {
if (shouldAbort(err)) return
client.query(insertProducts, (err, result) => {
if (shouldAbort(err)) return
client.query('UPDATE "synchProductsTasks" SET "totalCount" = $1, start = start + $2 WHERE "shopId" = $3', [r.totalCount, countPlus, task.shopId], (err, result) => {
if (shouldAbort(err)) return
client.query('COMMIT', err => {
done()
if (err) {
console.error('Error committing transaction', err.stack)
resolve({
status: false,
errorType: 'DatabaseError'
})
} else {
resolve({
status: true,
stage: 'next',
errorType: null
})
}
})
})
})
})
})
return
} else {
resolve({
status: true,
stage: 'finish',
errorType: null
})
}
resolve({
status: true,
})
}
})
.catch(err => {
resolve({
status: false,
errorType: 'RequestError'
})
})
} catch (err) {
console.error(2, err)
resolve({
status: false,
errorType: 'ServerError'
})
}
})
}
Answer the question
In order to leave comments, you need to log in
You need to refactor this module so that it does not make a request to an external service directly.
Then it will be possible for him, as part of the test, to slip a stub instead of a real client.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question