如何解决Jest Babel TypeScript类类型参数意外令牌
我遇到了Jest的问题,它无法理解类类型参数。
SyntaxError: /Users/john/dev/webpack-test/src/__tests__/utils.test.js: Unexpected token (18:40)
16 | describe('new Drawer()',() => {
17 | it('should add and remove socks',() => {
> 18 | const sockDrawer = new Drawer<Sock>();
我正在使用TypeScript游乐场中的类通用示例。
export class Drawer<ClothingType> {
contents: ClothingType[] = [];
add(object: ClothingType) {
this.contents.push(object);
}
remove() {
return this.contents.pop();
}
}
export interface Sock {
color: string;
}
export interface TShirt {
size: "s" | "m" | "l";
}
然后我有一个正在使用它的测试。我也在我的React应用程序中调用它,以确保它可以在那里编译并成功完成。
it('should add and remove socks',() => {
const sockDrawer = new Drawer<Sock>();
sockDrawer.add({ color: "white" });
expect(sockDrawer.contents).toEqual([{ color: 'white' }]);
const mySock = sockDrawer.remove();
expect(sockDrawer.contents.length).toEqual(0);
});
App Code编译正常。
{
"env": {
"test": {
"presets": [
[
"@babel/preset-env",{
"targets": {
"node": "10.17.0"
}
}
],"@babel/preset-react","@babel/preset-typescript"
],"plugins": [
"@babel/plugin-transform-runtime",["@babel/plugin-proposal-class-properties",{ "loose": true }]
]
}
}
这里的任何帮助将不胜感激。谢谢!
解决方法
解决此问题的方法是将以下配置添加到 Babel 配置中的 presets
。
[
"@babel/preset-typescript",{
"isTSX": true,"allExtensions": true,"jsxPragma": "react","onlyRemoveTypeImports": true
}
]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。