【问题标题】:Refactoring to reduce repitition in Mocha API test重构以减少 Mocha API 测试中的重复
【发布时间】:2021-06-19 23:23:22
【问题描述】:

在 Node.js 中运行 API 测试时,我经常发现自己重复了整个 it 语句块,但断言略有不同。这似乎是一种浪费,我希望它尊重 DRY 原则。

我们以以下为例:-

const { expect } = require('chai');
const got = require('got');
const core = require('../Libraries/CoreFunctions')


describe('Some description', function() {
  
  beforeEach(function() {
    
  })

    it('should do something', function(done) {
      got.get('https://someurl.com',
      {headers: core.headers()})
      .then(res => {
        core.respDateCode(res);
        console.log(core.prettyJSON(res));  
        expect(core.something).to.be.lessThan(2000);
        done()
      })
      .catch(err => {
        console.log('Error: ', err.message);
      });
    }).timeout(5000);
  
    

    it('should do something else', function(done) {
      got.get('https://someurl.com',
      {headers: core.headers()})
      .then(res => {
        core.respDateCode(res);
        console.log(core.prettyJSON(res));  
        expect(core.somethingElse).to.be.greaterThan(1000);
        done()
      })
      .catch(err => {
        console.log('Error: ', err.message);
      });
    }).timeout(5000);
  
  
  });
  

我正在寻找有关如何最好地重构上述内容以减少重复的建议?

【问题讨论】:

    标签: javascript mocha.js refactoring chai dry


    【解决方案1】:

    将获取的逻辑移到单独的文件中。然后,您可以将每个请求封装到一个函数中(没有参数,因此如果 API URL 更改,您的测试将不必更改)。每个测试都应该在“it”块中显式地调用被测函数,因此可以很快看出正在测试什么。如果你有很多重复的设置代码,你可以把它移到一个函数中。

    API 调用隔离的一个很好的副作用是,您最终会得到一个 API 客户端,它实际上是在与您的 API 同时进行测试的。

    不要担心您的测试代码会被高级别复制。基本上“给定这个设置,当被测函数被调用时,就会发生这种情况”。您可以将测试设置放入其他功能,但不要过度,因为您可能无法在查看测试时说出实际发生的情况。另外,永远不要抽象出被测函数。

    const { expect } = require('chai');
    const gotClient = require('../somewhere/client/uses/got');
    const core = require('../Libraries/CoreFunctions')
    
    describe('Some description', function() {
      
    
      it('should do something', async function(done) {
        // given
        const res = await gotClient.resource.getOne()
    
        // when
        core.functionThatIsBeingTested(res);
    
        // then
        expect(core.something).to.be.lessThan(2000);
        done()
      }).timeout(5000);
    
      it('should do something else', async function(done) {
        // given
        const res = await gotClient.resource.getOne()
        
        // when
        core.functionThatIsBeingTested(res);
        
        // then
        console.log(core.prettyJSON(res));  
        expect(core.somethingElse).to.be.greaterThan(1000);
        done()
      }).timeout(5000);
    });
    

    注意,这个版本和你的版本之间唯一真正的区别是在我的版本中你不需要关心 url 和 headers,这使得代码更具可读性和更容易理解。如果客户端以它正在获取的 API 命名,并且资源是资源的名称,那就更好了。

    举个例子:

    const res = await twilio.phoneNumbers.availableForPurchase()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-19
      • 2022-11-29
      • 2021-07-03
      • 2015-07-16
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 2013-02-04
      相关资源
      最近更新 更多