SSR的模拟服务器使用cypress.io对app e2e进行测试

时间:2017-12-04 10:59:45

标签: node.js testing nock ssr cypress

我正在构建一个带有服务器端呈现(SSR)的单页Web应用程序(SPA)。

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

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

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

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

2 个答案:

答案 0 :(得分:1)

我们使用了一种特别难看的解决方案,它打破了柏树的速度,但我们需要这样才能模拟/伪造套接字调用。

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

  • /上发布methodpath{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中。你将无法在外部存根。 (因此,为了在测试应用时请求localhost:xxxx而不是google.com,请创建一个env var)

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

答案 1 :(得分:0)

MockTTP可以做到。摘录自doc:

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");
        });
    );
});