Mocha & Chai로 Node API 테스트하기

모카란?



Mocha은 Node.js와 브라우저에서 실행되는 기능이 풍부한 JavaScript 테스트 프레임워크로, 비동기 테스트를 간단하고 재미있게 만듭니다.
  • 동기식 테스트 예

  • it('two plus two is four', () => {
        expect(2 + 2).to.equals(4);
      });
    

  • 비동기 테스트 코드

  • it("adds 2 numbers", (done) => {
       // perform asynchronous actions
       // write tests
        done(); // call the done function after test.
      });
    

    차이는 무엇입니까?



    Chai은 모든 자바스크립트 테스트 프레임워크와 즐겁게 결합할 수 있는 nodejs 및 브라우저용 BDD(행동 주도 개발)/TDD(테스트 주도 개발) 어설션 라이브러리입니다.

    어설션 유형



    Chai에는 개발자가 선택할 수 있는 여러 인터페이스가 있습니다. 그들은:

  • Should

  • chai.should();
    foo.should.be.a('string'); 
    foo.should.equal('bar');
    foo.should.have.lengthOf(3);
    tea.should.have.property('flavors').with.lengthOf(3);
    


  • Expect

  • var expect = chai.expect;  
    expect(foo).to.be.a('string'); 
    expect(foo).to.equal('bar'); 
    expect(foo).to.have.lengthOf(3); expect(tea).to.have.property('flavors').with.lengthOf(3);
    


  • Assert

  • var assert = chai.assert;  
    assert.typeOf(foo, 'string'); 
    assert.equal(foo, 'bar'); 
    assert.lengthOf(foo, 3);
    assert.property(tea, 'flavors'); 
    assert.lengthOf(tea.flavors, 3);
    

    서버 테스트



    이제 기본 Node API를 설정하고 이에 대한 테스트를 작성하는 과정을 안내하겠습니다.

    먼저 프로젝트 폴더를 만들고 npm으로 초기화하여 package.json 파일을 생성합니다.

    npm init -y
    

    터미널에서 아래 명령을 실행하여 종속성을 설치합니다.

    npm i express --save
    npm i mocha chai chai-http --save-dev
    

    설정 서버



    프로젝트의 루트에 app.js 파일을 생성하고 아래 코드를 추가하여 Express 및 테스트할 엔드포인트가 있는 서버를 생성합니다.

    const express = require("express");
    
    const app = express();
    
    app.use(express.json());
    
    app.get("/", (req, res) => {
      res.json({ status: "success", message: "Welcome To Testing API" });
    });
    
    app.post("/add", (req, res) => {
      const { num1, num2 } = req.body;
      const add = (num1, num2) => {
        return num1 + num2;
      };
      res.json({
        status: "success",
        result: "Welcome To Testing API",
        result: add(num1, num2)
      });
    });
    
    const PORT = process.env.PORT || 3000;
    
    app.listen(PORT, () => console.log(`App listening on port ${PORT}`));
    
    module.exports = app;
    
    

    설정 스크립트


    package.json 파일에 테스트 스크립트를 추가합니다.

    "scripts": {
        "test": "mocha"
      }
    

    테스트 작성



    프로젝트에 테스트 디렉터리를 만든 다음 생성된 app.test.js 디렉터리 안에 test 파일을 만듭니다.

    Note: The reason we're adding our tests to the test directory is that mocha searches for a test directory in your project by default, although this can be configured to suit your style. Find more here



    그런 다음 아래 코드를 추가하십시오.

    const app = require("../app");
    const chai = require("chai");
    const chaiHttp = require("chai-http");
    
    const { expect } = chai;
    chai.use(chaiHttp);
    describe("Server!", () => {
      it("welcomes user to the api", done => {
        chai
          .request(app)
          .get("/")
          .end((err, res) => {
            expect(res).to.have.status(200);
            expect(res.body.status).to.equals("success");
            expect(res.body.message).to.equals("Welcome To Testing API");
            done();
          });
      });
    
      it("adds 2 numbers", done => {
        chai
          .request(app)
          .post("/add")
          .send({ num1: 5, num2: 5 })
          .end((err, res) => {
            expect(res).to.have.status(200);
            expect(res.body.status).to.equals("success");
            expect(res.body.result).to.equals(10);
            done();
          });
      });
    });
    
    

    이 시점에서 폴더 구조는 아래 이미지와 같아야 합니다.


    테스트를 실행하려면 터미널에서 아래 명령을 실행하십시오.

    npm test
    

    테스트가 실행되고 테스트가 통과되면 아래 표시된 예와 같이 터미널에서 성공적인 응답을 받아야 합니다.


    ...테스트가 실패하면 아래 표시된 예와 같이 터미널에 오류 응답이 표시됩니다.


    Find the code used in this project on Github
    Find more information on Mocha here
    Find more information on Chai here



    결론



    이 기사에서는 Mocha 및 Chai로 테스트를 설정하고 Node API에 대한 테스트를 작성하는 방법을 살펴볼 수 있었습니다. Travis-CI라는 지속적인 통합 도구를 통합하기 위해 이 기사와 프로젝트를 개선할 것입니다.

    이 기사에 대한 질문이나 피드백이 있으면 언제든지 의견을 남겨주십시오.
    읽어 주셔서 감사합니다.

    좋은 웹페이지 즐겨찾기