NodeJS中的Jest + supertest,async / await

时间:2018-05-02 12:15:31

标签: javascript node.js async-await jest

我尝试用Jest测试我的api。我想要更多的抽象,所以我创建了这个函数:

const tokensConfig = config.get('test.tokens');

function testIt(method = 'get', url = '/', statuses = [], body = {}) {
      const testNames = ['unauthorized', 'user', 'admin'];
      const tokens = [null, tokensConfig.user, tokensConfig.admin];
    
      for (let i = 0; i < testNames.length; i++) {
        test(testNames[i], async () => {
          const response = await request(app)
            [method](url)
            .set('Accept', 'application/json')
            .set('Authorization', tokens[i])
            .send(body);
          expect(response.statusCode).toBe(statuses[i]);
        });
      }
    }

在test.js文件中我运行:

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

// It's work
describe('get user by email', () => {
    testIt('get', '/users/get-by-email/user@test', [401, 403, 200]);
  });
  
// It's not work  
describe('delete user', async () => {
    const userByEmail = await request(app)
      .get('/users/get-by-email/user@test')
      .set('Accept', 'application/json')
      .set('Authorization', config.get('test.tokens.admin'));

    testIt('delete', `/users/${userByEmail._id}`, [401, 403, 200]);
  });

async / await中的问题 - 在请求用户之前运行的testIt。

如果我移动测试(或它)从函数testIt描述块并在测试中创建请求用户,它将起作用。但是我想要更多的抽象(对于许多测试来说测试块非常大)

如何解决?

2 个答案:

答案 0 :(得分:1)

看起来你需要让jest知道期望是一种异步方法,<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:strip-space elements="*"/> <xsl:output method="xml" indent="yes"/> <xsl:variable name='QueryResult' select='document("test2018050202.xml")/QueryResult/Result'/> <xsl:template match='Invoice'> <Invoice> <xsl:apply-templates select='AdditionalDocumentReference'/> </Invoice> </xsl:template> <!-- By default, copy everything --> <xsl:template match="*|@*|text()|/"> <xsl:copy> <xsl:apply-templates select="*|@*|text()"/> </xsl:copy> </xsl:template> <!-- AdditionalDocumentReference with documentType=AKV should be replaced with AdditionalDocumentReference DocumentType=ABZ and the ID should replaced with the correct obj_license --> <xsl:template match="AdditionalDocumentReference[DocumentType='AKV']"> <xsl:copy> <DocumentType>ABZ</DocumentType> <ID><xsl:value-of select='$QueryResult[ac_name = current()/ID]/obj_license'/></ID> </xsl:copy> </xsl:template> </xsl:stylesheet>

以下是Jest的文档中的示例代码:

resolves

https://facebook.github.io/jest/docs/en/tutorial-async.html#async-await

答案 1 :(得分:0)

因此,我必须将测试移至test.js:

// testIt.js

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

const tokensConfig = config.get('test.tokens');

async function testIt(method = 'get', url = '/', body = {}) {
  const testNames = ['unauthorized', 'user', 'adminTokenExpired', 'admin'];
  const tokens = [null, tokensConfig.userTokenInfinity, tokensConfig.adminTokenExpired, tokensConfig.adminTokenInfinity];
  let result = [];

  for (let i = 0; i < testNames.length; i++) {
    const response = await request(app)
      [method](url)
      .set('Accept', 'application/json')
      .set('Authorization', tokens[i])
      .send(body);

    result.push(response.statusCode);
  }

  return result;
}

module.exports = testIt;

extension UINavigationController{

   func setNavBarImage(_ image:UIImage?) {

       guard let image = image  else {return}

       self.navigationBar.setBackgroundImage(image, for: .default)
       self.navigationBar.shadowImage = UIImage()
      self.navigationBar.isTranslucent = true

      //clear statusBar color
       let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView
       statusBar?.backgroundColor = UIColor.clear
    }
}

但是我不得不将自己局限于所有角色的一个答案,而是个人回答每个角色,因为我想要更少的代码。