syl*_*ain 8 testing node.js nock server-side-rendering cypress
我正在构建一个带有服务器端渲染 (SSR) 的单页 Web 应用程序 (SPA)。
我们有一个节点后端 API,它在 SSR 期间从节点服务器调用,在初始渲染后从浏览器调用。
我想编写 e2e 测试来配置 API 响应(如 with nock)并同时处理浏览器调用和 SSR 服务器调用。一些伪代码:
it('loads some page (SSR mode)', () => {
  mockAPI.response('/some-path', {text: "some text"}); // here i configure the mock server response
  browser.load('/some-other-page'); // hit server for SSR response
  expect(myPage).toContain('some text');
})   
it('loads some other page (SPA mode)', () => {
  mockAPI.response('/some-path', {text: "some other text"}); // here i configure another response for the same call
  browser.click('#some-link'); // loads another page client side only : no SSR here
  expect(myPage).toContain('some other text');
})   
目前 Cypress 允许我在浏览器上模拟 fetch,但不能在服务器上。
有什么可以实现的吗?最好使用节点库。
MockTTP可以做到这一点。摘自文档:
const superagent = require("superagent");
const mockServer = require("mockttp").getLocal();
describe("Mockttp", () => {
    // Start your server
    beforeEach(() => mockServer.start(8080));
    afterEach(() => mockServer.stop());
    it("lets you mock requests, and assert on the results", () =>
        // Mock your endpoints
        mockServer.get("/mocked-path").thenReply(200, "A mocked response")
        .then(() => {
            // Make a request
            return superagent.get("http://localhost:8080/mocked-path");
        }).then(() => {
            // Assert on the results
            expect(response.text).to.equal("A mocked response");
        });
    );
});
我们使用了一个特别丑陋的解决方案,它破坏了 cypress 的速度,但我们需要它来模拟/伪造套接字调用。
您可以制作一个真正简单的快速服务器,在运行测试之前启动它。这个“真假服务器”将能够响应您的需求。以下是我们的规格:
/在正文参数中使用method,path和进行 POST{data}以设置路线/path响应中的 GET/POST/PUT/DELETE{data}/清除所有路由让我们考虑一下您的“真实的假服务器”在 0.0.0.0:3000 上运行;你会做:
beforeEach() {
   cy.request('DELETE', 'http://0.0.0.0:3000/');
}
it('loads some page (SSR mode)', () => {
  cy.request('POST', 'http://0.0.0.0:3000/', {
    method: 'GET',
    path: '/some-path', 
    data: {text: "some other text"}
  }) // here i tell my 'real fake server' to 
     // respond {text: "some other text"} when it receives GET request on /some-path
  browser.load('/some-other-page'); // hit server for SSR response
  expect(myPage).toContain('some text');
})   
it('loads some other page (SPA mode)', () => {
  cy.request('POST', 'http://0.0.0.0:3000/', {
    method: 'GET',
    path: '/some-path', 
    data: {text: "some other text"}
  }); // here i configure another response for the same call
  browser.click('#some-link'); // loads another page client side only : no SSR here
  expect(myPage).toContain('some other text');
}) 
重要提示:请求需要位于本地主机中。你将无法存根外部的东西。(因此,在测试应用程序时,创建一个环境变量以便请求 localhost:xxxx 而不是 google.com)
除了这个 cy.request 之外,您将无法控制“真正的假服务器”,因为您的测试脚本在浏览器中运行(如果我错了,请纠正我)并且浏览器无法运行快速服务器。
| 归档时间: | 
 | 
| 查看次数: | 3267 次 | 
| 最近记录: |