gpt4 book ai didi

javascript - Mocha、Chai 和 Sinon 未处理的 promise 拒绝警告

转载 作者:搜寻专家 更新时间:2023-11-01 00:36:36 25 4
gpt4 key购买 nike

我正在使用 Node 并具有以下 ES6 类:

const moment = require('moment');

const sqlFileReader = require('../database/SqlFileReader');
const Lnfe = require('../errors/LoanNotFoundError');

const epoch = '1970-01-01';

/**
* Take the input params and return the clientId (either found via loanId or untouched) and dateString we need
*/
class ParameterParser {

static async prepareInputParameters(con, req) {

let clientId = req.query.client_id; // Will be overriden if we need and are able to obtain the client id via loan id.
let dateString;

// If no client_id is given but loan_id is, get the client_id via loan_id:
if (typeof req.query.client_id === 'undefined' && typeof req.query.loan_id !== 'undefined') {
const { retData } = await sqlFileReader.read('./src/database/sql/getClientIdFromLoanId.sql', [`${req.query.loan_id}`], con, req.logger);
if (retData.rowsCount > 0) {
clientId = retData.rows[0].client_id;
}
else {
throw new Lnfe(400, req);
}
}

if (typeof req.query.complaint_init_date === 'undefined') {
dateString = epoch;
}
else {
// Need to subtract 6 years from the complaint_init_date:
dateString = moment(moment(req.query.complaint_init_date, 'YYYY-MM-DD').toDate()).subtract(6, 'years').format('YYYY-MM-DD');
}

return { clientId, dateString };
}

}

module.exports = ParameterParser;

我正在使用 MochaChaiChai-as-PromisedSinon 对其进行测试:

'use strict';

const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const sinon = require('sinon');

const parameterParser = require('../../src/core/ParameterParser.js');
const sqlFileReader = require('../../src/database/SqlFileReader.js');
const Lnfe = require('../../src/errors/LoanNotFoundError');

chai.use(chaiAsPromised);
const { expect } = chai;

const retData = {
rowsCount: 1,
rows: [{ client_id: 872 }],
};

const reqDateAndLoan = {
query: {
complaint_init_date: '2022-03-15',
loan_id: '1773266',
},
};

const reqDateAndClient = {
query: {
complaint_init_date: '2022-03-15',
client_id: '872',
},
};

const reqDateAndLoanIdThatDoesNotExist = {
query: {
complaint_init_date: '2022-03-15',
loan_id: '1773266999999999999',
},
};

describe('prepareInputParameters', () => {

sinon.stub(sqlFileReader, 'read').returns({ retData });

it('results in correct client id and date string', async () => {
const ret = { clientId: 872, dateString: '2016-03-15' };
expect(await parameterParser.prepareInputParameters(null, reqDateAndLoan)).to.deep.equal(ret);
});

it('results in a client id equal to the that input if the request query contains a client id', async () => {
const ret = { clientId: '872', dateString: '2016-03-15' };
expect(await parameterParser.prepareInputParameters(null, reqDateAndClient)).to.deep.equal(ret);
});

it('throws a \'Loan Not Found\' error', async () => {
expect(parameterParser.prepareInputParameters(null, reqDateAndLoanIdThatDoesNotExist)).eventually.throw(Lnfe, 400, 'Loan Not Found');
});

it('DOES NOT throw a \'Loan Not Found\' error', async () => {
expect(async () => {
await parameterParser.prepareInputParameters(null, reqDateAndLoanIdThatDoesNotExist);
}).to.not.throw(Lnfe, 400, 'Loan Not Found');
});


});

测试通过但输出有几个 Node 警告:

prepareInputParameters
✓ results in correct client id and date string
✓ results in a client id equal to the that input if the request query contains a client id
✓ throws a 'Loan Not Found' error
(node:23875) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError: Loan Not Found: expected { Object (clientId, dateString) } to be a function
(node:23875) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
✓ DOES NOT throw a 'Loan Not Found' error


4 passing (19ms)

关于如何消除这些警告或我做错了什么有什么想法吗?

最佳答案

一些想法可以帮助您理解我使用 ES6 类编译的 promise 的不同阶段(示例,即):

//asyncpromiserejection.js

class asyncpromise{ 
constructor(s){
this.s=s
}
PTest(){
var somevar = false;
somevar=this.s;
return new Promise(function (resolve, reject) {
if (somevar === true)
resolve();
// else
// reject();
});
}
}
module.exports=asyncpromise

注释了 else 部分后,如果将 true 传递给类,则 promise 将解析,否则测试将超时,因为 promise 不知道在值为 false 时要做什么。

//测试.js

const asyncpromise=require('./asyncpromiserejection.js')
describe("asyncTests", () => {
it("handles Promise rejection",async ()=>{
var t=new asyncpromise(false)
await t.PTest().then(function () {
console.log("Promise Resolved");
})
})
});

图 1.0 Fig 1.0

取消对 else 部分的注释,你会得到同样的错误,但警告说 promise rejection has been deprecated - 图 1.1 - 因为现在,虽然由于错误值导致的 promise 拒绝在代码中处理,测试即。 ,调用方法,还没有处理它。

class asyncpromise{ 
constructor(s){
this.s=s
}
PTest(){
var somevar = false;
somevar=this.s;
return new Promise(function (resolve, reject) {
if (somevar === true)
resolve();
else
reject();
});
}
}
module.exports=asyncpromise

图 1.1 Fig 1.1

现在,像这样处理测试中的 promise 拒绝:

const asyncpromise=require('./asyncpromiserejection.js')
describe("asyncTests", () => {
it("handles Promise rejection",async ()=>{
var t=new asyncpromise(false)
await t.PTest().then(function () {
console.log("Promise Resolved");
}).catch(()=>{console.log("Promise rejcted")})
})
});

enter image description here

并且,您可以在 promise 的拒绝部分传递一些自定义消息,以在测试中断言,如下所示:

const assert=require('chai').assert
const asyncpromise=require('./asyncpromiserejection.js')
describe("asyncTests", () => {
it("handles Promise rejection",async ()=>{
var t=new asyncpromise(false)
await t.PTest().then(function () {
console.log("Promise Resolved");
}).catch((error)=>{
console.log("Promise rejected")
assert.equal(error.message,"Promise rejected")
})
})
});

//asyncpromiserejection.js

class asyncpromise{ 
constructor(s){
this.s=s
}
PTest(){
var somevar = false;
somevar=this.s;
return new Promise(function (resolve, reject) {
if (somevar === true)
resolve();
else
throw new Error("Promise rejcted")
//reject();
});
}
}
module.exports=asyncpromise

enter image description here

关于javascript - Mocha、Chai 和 Sinon 未处理的 promise 拒绝警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49498334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com