我需要对要获取的JS对象运行一个断言。这里的问题是,即使我的断言失败,测试仍然可以通过。我该如何解决?
代码:
<input value="20" type="checkbox" class="my-activity">
<input value="40" type="checkbox" class="my-activity">
<div id="infosp" class="fix-search"> SP need for selected levels: <input type="text" name="amount" id="amount" readonly=""> <input type="button" class="checka" value="Reload"> </div>
终端命令:
var expect = require('chai').expect
const sslCertificate = require('get-ssl-certificate')
describe('ssl certificate verification',()=>{
it('verifies the issuer of the certificate',()=>{
sslCertificate.get('instagram.com').then(function (certificate) {
console.log(typeof certificate.issuer)
console.log(certificate.issuer.O)
console.log(certificate.issuer.CN)
console.log(certificate.subject.CN)
expect(certificate.issuer).to.include({CN: 'DigiCert SHA2 High Assurance Server CA'});
expect(certificate.issuer).which.is.an('object').to.haveOwnProperty('CN')
})
})
})
输出
mocha myFile.js
断言失败,但通过测试输出
ssl certificate verification
√ verifies the issue of the certificate
1 passing (46ms)
object
DigiCert Inc
DigiCert SHA2 High Assurance Server CA
*.instagram.com
答案 0 :(得分:1)
当您使用异步代码(和Promise)时,会发生这种情况。从您的测试代码看来,方法sslCertificate.get()返回一个Promise。这个承诺将被异步解决(成功执行)或被拒绝(抛出错误)。在JS中,异步执行仅在当前同步执行暂停/完成后才开始。
在测试的上下文中,当承诺解析时,您将传递一个回调方法(使用.then())。此回调仅在承诺被解决后才会执行,并且由于您的测试代码不会为此执行而暂停,因此会成功完成-意味着sslCertificate.get('instagram.com')。then(callback)不会抛出任何错误或异常。执行测试后,promise就有机会解决,现在可以异步执行您的回调。因此,您会收到UnhandledPromiseRejectionWarning:AssertionError。
可以通过两种方式使用摩卡异步测试来解决此问题:
方法1:使用异步/等待(我个人为提高可读性而建议):
这是一些代码:
it('verifies the issuer of the certificate', async ()=>{ // This tells the test contains asynchronous code
const certificate = await sslCertificate.get('instagram.com'); // await gives a chance for the promise to resolve (in which case the certificate will be returned) or reject (in which case an exception will be thrown)
// You can now perform your assertions on the certificate
expect(certificate.issuer).to.include({CN: 'DigiCert SHA2 High Assurance Server CA'});
expect(certificate.issuer).which.is.an('object').to.haveOwnProperty('CN');
});
方法2:使用来自mocha的已完成回调-不是我最喜欢的用例-在有回调但不涉及承诺的情况下使用
添加'done'参数将强制Mocha等待直到调用了回调done()。现在,如果您的断言失败,将永远不会调用done(),并且测试将因超时错误(当然还有控制台中未处理的拒绝错误)而失败。尽管如此,测试仍将失败。
示例代码:
it('verifies the issuer of the certificate',(done)=>{ // Forces mocha to wait until done() is called
sslCertificate.get('instagram.com').then(function (certificate) {
expect(certificate.issuer).to.include({CN: 'DigiCert SHA2 High Assurance Server CA'});
expect(certificate.issuer).which.is.an('object').to.haveOwnProperty('CN');
done(); // All assertions done.
});
});
更多来自官方文档的详细信息:https://mochajs.org/#asynchronous-code