如何自动化测试用户旅程?

How to automate testing a user journey?

我使用 NodeJS 作为 Web 服务器,使用 Mocha 进行测试。我尝试了这个测试以确保应用程序可以创建用户、注销并再次登录:

const request = require('supertest');
const app = require('../app');

const req = request(app);

describe("user journey", function() {
  it("tests a user journey (signup, logout, sign in)", function(done) {
    let signedInStub = "something only for logged in users";
    req
      .post("/signup")
      .send({
        "email": "test@test.com",
        "password": "abcd1234"
      })
      .expect(function(response) {
        expect(response.body.includes(signedInStub))
      })
      .get("/logout")
      .expect(function(response) { // <-- Test fails here.
        !response.body.includes(signedInStub)
      })
      .post("/login")
      .send({
        "email": "test@test.com",
        "password": "abcd1234"
      })
      .expect(function(response) {
        response.body.includes(signedInStub)
      })
      .get("/content/2")
      .expect(200, done);
  });
});

我 运行 它与 mocha --exit test.js 并得到错误:

  1) user journey
       tests a user journey (signup, logout, sign in):
     TypeError: Cannot read property 'expect' of undefined

如何在命令行上测试用户可以创建帐户、注销和登录?

创建一个 agent 并在多个请求中使用它来保持会话。

如果需要,请安装 chai,它适用于 supertest,适用于 npm install --save chai。 (有关使用 Mocha 和 Chai 在 NodeJS 中进行测试的详细信息,请参阅 here。)

如果您使用的是 cookie 以外的身份验证类型,请以相同的方式将数据保存在变量中并随每个请求一起发送。

const request = require('supertest');
const app = require('../app');

const { expect } = require('chai')

const User = require('../models/user');
const email = "test@test.com";

describe("user journey", function() {

  let req
  let signedInStub = "something only for logged in users"

  before(function(){
    req = request.agent(app)
  })

  it("should signup a new test@test.com user", async function() {

    // Delete this email in case emails are unique in the database.
    await User.deleteOne({email: email});

    const response = await req.post("/signup")
      .send({
        "email": email,
        "password": "abcd1234"
      })
      .redirects(1); // optional, in case your back-end code uses a redirect after signing up.
    // Log the response so you can track errors, e.g. hidden parameters in the HTML form that are missing from this POST request in code.
    console.log(response.text);
    expect(response.text).to.include(signedInStub)
  })

  it("should logout the new user", async function() {
    const response = await req.get("/logout")
    expect(response.text).not.to.include(signedInStub)
  })

  it("should login the new user", async function() {
    const response = await req.post("/login")
      .send({
        "email": email,
        "password": "abcd1234"
      })
    expect(response.text).to.include(signedInStub)
  })

  it("should get the new users content", async function() {
    await req.get("/content/2")
      .expect(200)
  });
});