gpt4 book ai didi

javascript - Jest 单元测试 'Function' 返回 SyntaxError : Unexpected identifier at Function ()

转载 作者:行者123 更新时间:2023-11-28 20:36:05 25 4
gpt4 key购买 nike

我们有一个调用wraps leaflet的stencil app,style函数需要把一个Function作为方法参数,stencil做不到,所以我们传递一个对象,然后解析成一个函数,反正这样可以但是尝试用 Jest 测试它给我们带来了问题。

代码

public onStylesChange(newVal) {
this.geoJSONstyles = Function('return ('+newVal+')')(); //
if (this.geoJSON) {
this.geoJSON.setStyle(this.geoJSONstyles);
}
}
}

测试

it('Should accept a function parameter', () => {
cut.onObjChange({test:'object'});
// expect the cut.geoJSONStyles property to be of type Function.
expect(typeof cut.geoJSONstyles).toBe('Function');
})

返回

SyntaxError: Unexpected identifier
at Function (<anonymous>)

我该如何解决?

最佳答案

不知道去年我的脑袋在哪儿,但休息一下让我的思路清晰了。

我需要做的是检查类型,我可以在评论中向我指出这一点,所以我需要做的是检查类型,我也可以将函数作为字符串返回并检查它。(忽略函数的作用,它只是为了测试分配)所以

it('Should accept a string function and eval to a function', () => {
const testString = 'function () {return 0 }'
cut.onObjChangetest(String);
expect(typeof cut.onEachFeature === 'function').toBeTruthy();
expect(cut.geoJSONstyles.toString()).toBe(testString);
})

完美运行,测试通过,哇哦!谢谢

关于javascript - Jest 单元测试 'Function' 返回 SyntaxError : Unexpected identifier at Function (<anonymous>),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53884561/

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