这应该是一个非常简单的问题,所以很可能我忽略了一些东西。
我正在尝试通过 Playwright 在浏览器中测试 JS 库模块。此设置包括三个文件:
export default function randomFn() {
let a = 1
return a + 2
}
import randomFn from './index.js'
window.randomFn2 = randomFn
import path from 'path';
import { expect, test as it } from '@playwright/test';
const { describe } = it;
const moduleFile = path.resolve(__dirname,"..","src", 'index_browser.js');
describe('Example', () => {
it('should test', async ({ page }) => {
await page.addScriptTag({
path: moduleFile,
type: "module"
})
const result = await page.evaluate(
() => {
return randomFn2()
},
[],
);
console.log(result)
});
});
运行此代码时,evaluate 函数未找到 randomFn 函数(它仍然未定义)。
如果我删除包装函数中的导入,然后像这样嵌入 randomFn 函数:
export default function randomFn() {
let a = 1
return a + 2
}
window.randomFn2 = randomFn
一切都按预期进行。是否缺少某些内容导致此问题?
我提供了一个示例项目来直接查看代码。
相关问题/答案:
我不确定这是否是一个令人满意的答案,但我也不完全清楚您的实际用例是什么。我将保留它,希望它足以诊断问题并提出适合您的用例的解决方案(或者稍后我会提出更明确的解决方案/解释)。
问题似乎是
./index.js
没有指向已提供的文件,因此您应该看到类似 的错误
Uncaught TypeError: Failed to resolve module specifier "./index.js".
Invalid relative url or base scheme isn't hierarchical.
at addScriptContent (eval at evaluate (:201:30)
解决方法是从已知位置提供脚本启用 CORS,例如:
npm install http-server -g
http-server -p 8000 --cors # run inside project root
然后使用指向服务器的 URL:
import randomFn from 'http://localhost:8000/src/index.js'
window.randomFn2 = randomFn