模板 e2e 测试:在木偶浏览器上下文中模拟函数



我有Stencil组件,它使用axios.get从服务器获取一些数据(例如,在开发过程中的localhost:3000)。 现在我有一个 e2e.ts 测试,它结合其他几个组件测试此组件。 我想模拟 axios.get 函数以将我的测试与服务器隔离开来。 在spec.ts测试中,我会使用以下代码使用jest来模拟axios:

import axios from 'axios';
import {myComponent} from './my-component';
const mock = jest.spyOn(axios, 'get');
test('get data', async () => {
...
mock.mockResolvedValue('hello');
...
});

但这在 e2e 测试中不起作用。 我尝试过安装jest-puppeteer,但我找不到任何示例来说明如何使用jest-puppeteer模拟API来模拟函数。

任何示例代码将不胜感激。

附注:如果我使用Puppeteer拦截请求并响应它,我会收到"请求已处理"错误。 下面是示例代码:

const page = await newE2EPage();
await page.setRequestInterception(true);
page.on('request', req => {
if(req.url() === 'http://localhost:3000/') {
request.respond({
contentType: 'text/plain',
headers: {'Access-Control-Allow-Origin': '*'},
body: 'hello'
})
}
else {
request.continue({});
}
});
await page.setContent('<my-component></my-component>');

我不是 100% 确定这个答案翻译成axios的程度如何,但这可以通过fetch来实现,我鼓励您使用,因为它现在被浏览器广泛支持,并且 Stencil 会在需要时自动对其进行多填充。

对于我们应用程序的 e2e 测试,我编写了以下脚本,您可以在启动它后将其添加到 e2e 页面:

await page.addScriptTag({
content: `
window.originalFetch = window.fetch;
window.requestsToIntercept = [];
window.fetch = (...args) => (async(args) => {
const result = await this.originalFetch(...args);
for (const request of requestsToIntercept) {
if (args[0].includes(request.url)) {
result.json = async () => JSON.parse(request.response);
result.text = async () => request.response;
}
}
return result;
})(args);`,
});

它覆盖fetch实现,并使用全局requestsToIntercept数组来存根响应。您可以在代码中添加一个帮助程序函数,例如

const interceptRequests = async (requests: { url: string; response: string }[]) =>
page.addScriptTag({
content: `window.requestsToIntercept.push(...${JSON.stringify(requests)});`
});

然后像这样使用它

interceptRequests([{ url: '/foo', response: { foo: 'bar' } }])

这将拦截包含/foo的所有请求,并改为使用给定的响应进行响应。


我会让你按照你想要的方式将其重构为帮助程序。就我个人而言,我决定创建一个函数,为我创建一个newE2EPage,并将interceptRequests作为方法添加到页面对象。


顺便说一句,您无法在 Puppeteer 中启用请求拦截的原因是 Stencil 已经在内部使用它,因此在您的"请求"侦听器启动之前,请求已经得到处理(如错误消息所述)。在Github上有一个更改它的请求:https://github.com/ionic-team/stencil/issues/2326。

相关内容

最新更新