这是我的 TS 代码:
export class MyClass {
private myElement: HTMLElement;
constructor() {
this.myElement = document.getElementById("ID") as HTMLElement;
if (!this.myElement) {
throw new Error("myElement is missing")
}
}
}
这是我的笑话测试:
it("should not throw an error", () => {
document.body.innerHTML = "<div id='ID'>some text</div>";
const sut = new MyClass();
});
这是我的 jest.config.js:
module.exports = {
preset: "ts-jest",
testEnvironment: "jsdom"
}
我的package.json:
{
...
"scripts": {
"test": "jest"
},
"devDependencies": {
"@types/jest": "^29.5.12",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"ts-jest": "^29.1.2",
"ts-loader": "^9.5.1",
"typescript": "^5.4.2",
"webpack": "^5.90.3",
"webpack-cli": "^5.1.4"
}
}
由于某种原因,我在单元测试中创建的
div
似乎被忽略,并且实现抛出错误:“myElement 丢失”。
有人能发现我的设置有问题吗?预先感谢您!
无法重现。假设我导入文件,你的代码在 Ubuntu 22.04 上对我来说工作得很好:
t.test.ts:
import { MyClass } from "./t";
it("should not throw an error", () => {
document.body.innerHTML = "<div id='ID'>some text</div>";
const sut = new MyClass();
expect(document.querySelector("#ID").textContent).toBe("some text");
});
t.ts:
export class MyClass {
private myElement: HTMLElement;
constructor() {
this.myElement = document.getElementById("ID") as HTMLElement;
if (!this.myElement) {
throw new Error("myElement is missing")
}
}
}
package.json:
{
"scripts": {
"test": "jest"
},
"devDependencies": {
"@types/jest": "^29.5.12",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"ts-jest": "^29.1.2",
"ts-loader": "^9.5.1",
"typescript": "^5.4.2",
"webpack": "^5.90.3",
"webpack-cli": "^5.1.4"
}
}
jest.config.js:
module.exports = {
preset: "ts-jest",
testEnvironment: "jsdom"
}
运行:
$ npm i
$ npm run test
> test
> jest
ts-jest[config] (WARN) message TS151001: If you have issues related to imports, you should consider setting `esModuleInterop` to `true` in your TypeScript configuration file (usually `tsconfig.json`). See https://blogs.msdn.microsoft.com/typescript/2018/01/31/announcing-typescript-2-7/#easier-ecmascript-module-interoperability for more information.
PASS ./t.test.ts
✓ should not throw an error (11 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.072 s
Ran all test suites.