【发布时间】:2018-04-15 05:18:21
【问题描述】:
我正在尝试用 Go 编写一个 JavaScript 测试套件。
我设想使用 Go 创建单元测试,并针对加载在浏览器中的 Web 应用程序运行它们。
为此,我将test JavaScript 对象放入全局命名空间;因此,我对要测试的不同组件有一个“钩子”。
是否可以在 Chrome 中加载此脚本,并将接口公开给test,以便我可以从 Go 访问浏览器内的 JavaScript 函数?
例子:
// JavaScript 函数
// Intentionally, and cautiously, emplace "test" into the global namespace
// In practice I would make this a singleton :^D
test = (typeof test == "undefined") ? {} : test;
// Employ the method invocation pattern to append "test" with function "cheesePrice()"
// ES6 fat arrow function
test.cheesePrice = (type) => {
let p = 0;
switch (type) {
case "cheddar" : { p = 9.99; break; };
case "swiss" : { p = 6.49; break; };
case "gouda" : { p = 7.49; break; };
default : { // throw; }
}
return p;
}
// Example call
test.cheesePrice("swiss"); //-> 6.49
鉴于上述情况,我如何在 Go 脚本中调用 test.cheesePrice() 并接收返回值?像这样的东西(伪编码);
// Imagine here browserHook is an interface into Chrome
// Enabling us to invoke the method above
func getJsCheesePrice(cheeseType string) float32 {
return browserHook.test.getPrice(cheeseType);
}
func main() {
assert.Equal(getJsCheesePrice("cheddar"), 9.99);
}
【问题讨论】:
标签: javascript google-chrome testing go interface