Stenciljs单元测试得到错误:未定义ReferenceError XMLHttpRequest

时间:2020-05-21 07:38:54

标签: unit-testing jestjs stenciljs

我正在尝试为我的模板js组件创建单元测试,在compnentWillLoad()方法中它将执行HTTP请求(使用rxjs)。当我运行测试时出现错误 ReferenceError:XMLHttpRequest是未定义。但是当从componentWillLoad()方法中删除HTTP请求时,测试通过了。 我的测试如下,

it('should render my component', async () => {
    const page = await newSpecPage({
      components: [MyComponent],
      html: `<my-component></my-component>`,
    });
    expect(page.root).toEqualHtml(`<my-component></my-component>`);
  });

我遇到错误 ReferenceError:未定义XMLHttpRequest

2 个答案:

答案 0 :(得分:0)

在使用XMLHttpRequest时创建的虚拟DOM上下文中确实没有定义

newSpecPage

最适合您的解决方案可能是使用newE2EPage将此作为E2E测试编写,它更适合于完整的端到端测试,因为它运行在{{1 }}。

XMLHttpRequest

“规格页面”测试实际上是针对独立工作的单元测试组件。如果您的目标是实际对组件进行单元测试,而您只想实例化您的组件,但实际上并不需要成功进行测试的请求,那么您也可以使用Stencil的it('should render', async () => { const page = await newE2EPage({ html: '<my-component></my-component>' }); const myComponent = page.find('my-component'); expect(myComponent).toHaveClass('hydrated'); }); 上下文:

Build

答案 1 :(得分:0)

我在使用 StencilJestXMLHttpRequest 时遇到了类似的问题。

首先,确保你打电话

new window.XMLHttpRequest()

而不是简单地调用

new XMLHttpRequest()

seems to be neccessary when using jsdom 可能已经解决了您的问题。

虽然它没有解决我的问题,因为我想确保没有真正的 API 调用正在进行。所以我试图模拟 XMLHttpRequest。但是,我在构建模拟时遇到了其他问题,最终决定重构我的代码以使用 Fetch API 而不是 XMLHttpRequest which seems to be better supported by Stencil

您可以使用 jest 轻松模拟 fetch

export function mockFetch(status, body, statusText?) {
  // @ts-ignore
  global.fetch = jest.fn(() =>
    Promise.resolve({
      status: status,
      statusText: statusText,
      text: () => Promise.resolve(JSON.stringify(body)),
      json: () => Promise.resolve(body),
    })
  )
}