Converting Mocha api test from async await to Supertest

mocha describe async
request supertest await
npm api testing
jest api testing
supertest check response body
mocha async/await
supertest timeout
supertest https

i have following question, i start writing API test, now it's look like:

  xit('should add address ', async () => {
    const result = await request({
      headers: Object.assign(config.headers, { 'Authorization': 'Bearer '+auth_token }),
      url: `${config.url}/rest/v1/address/`,
      method: "POST",
      json: {
        "name": generatedAddressName,
        "city": "WARSZAWA",
        "street": "UL. KASPROWICZA",
        "houseNumber": "49XX",
        "apartNumber": "",
        "lat": 52.176903,
        "lng": 21.028369,
        "zipCode": "02-732",
        "isDefault": false,
        "inDeliveryZone": true
      }
    });
  });

not sure if this will work, but it should be:

it('should add address supertest', async function(done) {
 const res = await request
  .post('/rest/v1/address/')
  .set(config.headers)
  //.set('Accept', 'application/json')
  .set('Authorization', 'Bearer ' + auth_token)    
  .send({
    "name": generatedAddressName,
    "city": "WARSZAWA",
    "street": "UL. KASPROWICZA",
    "houseNumber": "51",
    "apartNumber": "",
    "lat": 52.176903,
    "lng": 21.028369,
    "zipCode": "02-732",
    "isDefault": false,
    "inDeliveryZone": true
  })
  .expect(200)
  .catch(done)   
 done()
});  

there is a section in https://github.com/visionmedia/supertest that talks about promises.

javascript, i have following question, i start writing API test, now it's look like: xit('should add address ', async () => { const result = await request({ headers:  The problem with this combination is the test code can get pretty darn caught up in boilerplate callback functions, if you use Mocha and SuperTest the way its documented. Fortunately it's pretty easy to make SuperTest return a Promise, which then plays well with async functions, and Mocha is easily able to use an async function in a test scenario.

Ok, about your error: you need to import your app and pass it as a parameter to request, like this:

request(app).post(...

Now about the async await: this is what your code should look like

it('should add address supertest', async () => {
  const res = await request(app)
    .post('/rest/v1/address/')
    .set(config.headers)
    //.set('Accept', 'application/json')
    .set('Authorization', 'Bearer ' + auth_token)    
    .send({
      "name": generatedAddressName,
      "city": "WARSZAWA",
      "street": "UL. KASPROWICZA",
      "houseNumber": "51",
      "apartNumber": "",
      "lat": 52.176903,
      "lng": 21.028369,
      "zipCode": "02-732",
      "isDefault": false,
      "inDeliveryZone": true
    })

  expect(res.statusCode).to.equal(200);
});

Edit: Note this on supertest documentations

Blockquote You may pass an http.Server, or a Function to request() - if the server is not already listening for connections then it is bound to an ephemeral port for you so there is no need to keep track of ports.

I don't think passing an URL to request() will work

Streamline Mocha/SuperTest REST tests with async functions, Streamline Mocha/SuperTest REST tests with async functions The code within that async function can then use the await keyword, thrown That is - SuperAgent builds on the SuperTest API, so the best source for  I’ve been playing around with refactoring a Koa application to use modern JavaScript constructs like async, await => and do away with generators etc. In doing so I had an epic battle with mocha, monk and supertest to use async / await etc. I finally found a good structure for this purpose that I wanted to share.

@iagowp I wrote the code as in your example, and it throws me

  1) 0_auth
       should return token for unauthorized user:
     Error: incorrect header check
      at Unzip.zlibOnError (zlib.js:153:15)

const chai = require('chai');
//const request = require('request-promise-native');
const mocha = require('mocha');
const config = require('../config');
const request = require('supertest');
const assert = chai.assert;
auth_token = '';


describe('0_auth', () => {
    it('should return token for unauthorized user', async () => {
    const res = await request(url)
      .post('/rest/v1/auth/get-token')
      .set(config.headers)
      //.set('Accept', 'application/json')  
      .send({
          "deviceUuidSource": "DEVICE",
          "source" : "KIOSK_KFC",
          "deviceUuid" : "uniquedeviceuuid"
      })
      .end(function(err,res){
        assert.equal(res.status,200)
        assert.property(res.body, 'token')
        assert.isString(res.body.token)
        auth_token=res.body.token
        console.log('unathorized token: '+auth_token) 
        done(err);
      });    
      expect(res.statusCode).to.equal(200);   
   });


   it('should return token for authorized user', async () => {
    const res = await request(url)
      .post('/rest/v1/auth/with-password')
      .set(config.headers)
      .set('Authorization', 'Bearer ' + auth_token) 
      //.set('Accept', 'application/json')  
      .send({
        "email" : user,
        "password" : password
      })
      .end(function(err,res){
        assert.equal(res.status,200)
        assert.property(res.body,'token')
        assert.isString(res.body.token)
        assert.equal(res.body.user.email,user)
        assert.isFalse(res.body.user.locked)
        auth_token=res.body.token
        console.log('authorized token: '+auth_token) 
        done(err)
      });  
      expect(res.statusCode).to.equal(200);       
   });

});

Automating Async API testing in JavaScript using Mocha, Chai , A RESTful API is an application programming interface that uses HTTP requests Automating Async API testing in JavaScript using Mocha, Chai & Supertest By putting await the interpreter knows that it has to wait for this http call to return a​  Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting while mapping uncaught exceptions to the correct test cases. In other words, mocha is a javascript test framework. Chai

Run or Debug integration test with nodeJs using typescript, Mocha , Mocha, Chai and SuperTest for async/await node api-functions - node.js. I am trying to run(using command npm run test and to debug i have been used IDE I can use some sync lib to convert migration to be synchronous but I would like​  Mocha. For our overall testing framework we’re using TJ Holowaychuk’s Mocha which has been working out really well. Mocha does all the basic things I’d expect in a testing framework and deals nicely with Node’s asynchronous nature. I won’t tell you too much about Mocha because I think the documentation is

A step-by-step intro to end-point testing, I tried Tap, Tape, Mocha, Jasmine, and AVA. Note: Here's an article on Async/​await in JavaScript if you don't know how to use it. To use Supertest, you require your app and supertest in the test file. This line converts fs.readdir into a promise const readDir = util.promisify(fs.readdir); async function  Step 4 - Create a test database In the part one of this article, we created two databases, one for development and the other for testing. Follow the link to create a test database if you have not done so. Step 5 - Configure test scripts. We need the following scripts: pretest - The pretest is an npm script that is automatically invoked when the

Converting your Unit and End-To-End Test Suites from Mocha, Chai , Mocha is a feature-rich JavaScript test framework running on Node.js I built a Mock Premier League Fixture API so as to demonstrate how you can jest and @shelf/jest-mongodb and supertest(used for end-to-end tests) //Used by both unit and e2e tests export const closeDatabase = async () => { await  However, in this case you can simplify it even further by just returning the promise and not using the test done parameter at all, since Mocha will wait for the promise to succeed or fail as indicating test success or failure (provided there's no done parameter to the test function; behavior in the event both are used is still being hashed out):

Comments
  • you may even be able to get rid of the done() at the base of the function and just return the request. not sure...
  • in case if I test webservice, not a local application - where i should put url to service?
  • At the same place.
  • ok, now i have: const res = await request(url) under 'it' and above:' const request = require('supertest')(url);' Still have 'TypeError: request.post is not a function, what's wrong?
  • The correct is: const request = require('supertest'); Then const res = await request(url).post..... Also, note the edit on my answer
  • check my newest comment below