【问题标题】:How to use the beforeEach in node-tap?如何在 node-tap 中使用 beforeEach?
【发布时间】:2016-07-11 02:54:07
【问题描述】:

有人可以举例说明如何使用beforeEach吗? http://www.node-tap.org/api/ 理想情况下,promise 版本的示例,但回调版本的示例也很好。

这是我创建的一个运行良好的测试:

'use strict';

const t = require('tap');
const tp = require('tapromise');
const app = require('../../../server/server');
const Team = app.models.Team;

t.test('crupdate', t => {
  t = tp(t);

  const existingId = '123';
  const existingData = {externalId: existingId, botId: 'b123'};
  const existingTeam = Team.create(existingData);

  return existingTeam.then(() => {
    stubCreate();

    const newId = 'not 123'
    const newData = {externalId: newId, whatever: 'value'};
    const newResult = Team.crupdate({externalId: newId}, newData);

    const existingResult = Team.crupdate({externalId: existingId}, existingData);

    return Promise.all([
      t.equal(newResult, newData, 'Creates new Team when the external ID is different'),
      t.match(existingResult, existingTeam, 'Finds existing Team when the external ID exists')
    ]);
  });
})
.then(() => {
  process.exit();
})
.catch(t.threw);


function stubCreate() {
  Team.create = data => Promise.resolve(data);
}

在我做任何事情之前,我想坚持existingTeam。保存后,我想存根Team.create。在这两件事之后,我想开始实际测试。我认为如果不使用Promise.all 或者复制测试代码,我可以使用beforeEach,这样会更简洁。

如何将其转换为使用beforeEach?或者它的用法有什么例子?

【问题讨论】:

    标签: javascript node.js unit-testing tap


    【解决方案1】:

    简单,只需从回调函数返回promise

    const t = require('tap');
    const tp = require('tapromise');
    const app = require('../../../server/server');
    const Team = app.models.Team;
    
    const existingId = '123';
    const existingData = {
      externalId: existingId,
      botId: 'b123'
    };
    
    t.beforeEach(() => {      
      return Team.create(existingData).then(() => stubCreate());
    });
    
    t.test('crupdate', t => {
      t = tp(t);
    
      const newId = 'not 123'
      const newData = {
        externalId: newId,
        whatever: 'value'
      };
      const newResult = Team.crupdate({
        externalId: newId
      }, newData);
    
      const existingResult = Team.crupdate({
        externalId: existingId
      }, existingData);
    
      return Promise.all([
        t.equal(newResult, newData, 'Creates new Team when the external ID is different'),
        t.match(existingResult, existingTeam, 'Finds existing Team when the external ID exists')
      ]);
    }).then(() => {
      process.exit();
    }).catch(t.threw);
    
    
    function stubCreate() {
      Team.create = data => Promise.resolve(data);
    }
    

    【讨论】:

    • 我现在明白了。 t.test 函数就像 then 对从 beforeEach 返回的任何内容。
    猜你喜欢
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多