12

我正在使用服务器端渲染 (SSR) 构建单页 Web 应用程序 (SPA)。

我们有一个节点后端 API,它在 SSR 期间从节点服务器调用,在初始渲染后从浏览器调用。

我想编写配置 API 响应的 e2e 测试(例如 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');
})   

目前赛普拉斯允许我在浏览器上模拟获取,但不能在服务器上模拟。

有什么可以实现的吗?最好使用节点库。

4

2 回答 2

7

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");
        });
    );
});
于 2018-07-20T09:56:33.467 回答
3

我们使用了一个特别丑陋的解决方案,它破坏了 cypress 的速度,但我们需要它来模拟/伪造套接字调用。

您可以制作一个真正简单的快速服务器,在运行测试之前启动。这个“真正的假服务器”将能够响应您的需求。以下是我们的规格:

  • POST on /with method, pathand {data}in body 参数以设置路线
  • GET/POST/PUT/DELETE/path响应{data}
  • DELETE/清除所有路线

让我们考虑您的“真正的假服务器”在 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');
}) 

重要提示:resquests 需要在 localhost 中。你将无法存根外部的东西。(因此,当您测试您的应用程序时,请创建一个 env var 以请求 localhost:xxxx 而不是 google.com)

除了这个 cy.request 之外,您将无法控制“真正的假服务器”,因为您的测试脚本在浏览器中运行(如果我错了,请纠正我)并且浏览器无法运行快速服务器。

于 2018-04-13T12:27:01.417 回答