我在 Chrome 浏览器中使用 Mocha 和 Chia 设置了单元测试,如下所示。为了强制 Component 类的静态 htmlTagName 属性,我在 Component 基类中使用了一个错误,如果 htmlTagName 属性没有被子类覆盖,则会抛出该错误。我遇到的问题是构造函数中抛出的错误似乎没有被 chia.assert.throw(...) 捕获,而是导致测试失败,如下面的链接所示。我期望看到的行为是 chia 捕获了预期的错误并且测试通过了。我在下面包含了相关代码。
<!DOCTYPE html>
<!-- index.html -->
<html>
<head>
<title>Mocha Tests</title>
<link rel="stylesheet" href="../../node_modules/mocha/mocha.css">
</head>
<body>
<div id="mocha"></div>
<script src="../../node_modules/mocha/mocha.js"></script>
<script src="../../node_modules/chai/chai.js"></script>
<script type="module" class="mocha-init">mocha.setup('bdd')</script>
<!-- load code you want to test here -->
<!-- load your test files here -->
<script type='module' src="./objective-styles.test.js"></script>
<script type='module' src="./base-classes.test.js"></script>
<script type='module' src="./calendar-widget.test.js"></script>
<script type="module">
mocha.run();
</script>
</body>
</html>
//base-classes.ts
export class Component extends HTMLElement {
static htmlTagName: string | undefined;
constructor() {
super();
// Enforce classes having htmlTagName
if(!this.htmlTagName) {
throw (`${this.constructor.name} htmlTagName property is undefined`);
}
}
get htmlTagName() {
return this.constructor.htmlTagName;
}
set htmlTagName(htmlTagName: string) {
this.constructor.htmlTagName = htmlTagName;
}
}
// base-classes.test.ts
import { GuiTestingUtils } from "./gui-testing-utils.js";
import { Component, Widget} from "../../app/js/widgets/base-classes.js";
describe("Component test suite", ()=>{
let sandbox: HTMLDivElement;
let fakeDOM: ShadowRoot;
let style: HTMLStyleElement;
before(()=>{
// set up the sandbox
let body = document.querySelector('body');
sandbox = GuiTestingUtils.addSandbox(body!);
fakeDOM = sandbox.shadowRoot!;
style = document.createElement('style');
});
beforeEach(()=>{
// clean the sandbox
GuiTestingUtils.refreshSandbox(sandbox);
fakeDOM.appendChild(style);
});
after(()=>{
// tear down the sandbox
let body = document.querySelector('body');
body!.removeChild(sandbox);
});
it("Component does throw error if htmlTagName is not defined", ()=>{
// chia.assert.throw does not catch the error as expected...
customElements.define("base-component", Component);
chai.assert.throw(()=>{
document.createElement("base-component");
});
});
});