Почему это ожидание не оправдывается - sinon + Parse Server afterSave? - PullRequest
1 голос
/ 24 января 2020

Код, который я пытаюсь протестировать, представляет собой функцию afterSave сервера Parse, запускаемую после сохранения экземпляра модели Parse (создан / обновлен и т. Д. c). Я пытаюсь проверить, что вызов .initiate выполняется всякий раз, когда пользователь сохраняется.

В основном это так:

Parse.Cloud.afterSave('user', function(request, response) {
    try{
        let user = request.user;
        // ... condition that triggers another workflow for event USER_CREATED

        // But I'm interested in making sure this runs:
        UserTriggerService.initiate(user, 'USER_ACTIVITY_UPDATED');
    } catch(err) {
    }
    response.success();
});

И вот как я его проверяю:


describe('workflows', () => {
  let sandbox;

  before(async () => {
    // Use sinon for certain mocks
    sandbox = sinon.sandbox.create();

    // Start Mongo Direct Connection
    await Mongo.connect();
  });

  afterEach(() => {
    sandbox.restore();
  });

  after(() => {
    return Mongo.db.dropDatabase();
  });

  it('should apply NO_TASKS workflow to user and increase their task count after its updated to 0', async () => {
    let user1 = new WorkOrder({
      username: 'testUser',
      email: 'testUser@test.com',
      taskCount: 100,
    });

    // User is created
    let userInst = await user1.create();

    let mock = sandbox.mock(WorkflowService);

    // This is because when the user is created above, I need to mock USER_CREATED workflow details
    mock
      .expects('getFlowData')
      .atLeast(1)
      .withArgs(user.get('role').id, 'USER_CREATED')
      .returns(
        Promise.resolve(null), // mocking that no workflow exists for this event
      );

    /* Mock user task count update to 0 */
    let updatedUser = new _User(userInst);
    updatedUser.set('taskCount', 0);
    updatedUser = await updatedUser.update();
    // await WorkflowService.initiate(updatedUser, 'NO_TASKS'); // uncommenting this makes the test successful, but that beats the point of the test

    mock
      .expects('getFlowData')
      .atLeast(1)
      .withArgs(user.get('role').id, 'NO_TASKS')
      .returns(
        Promise.resolve([
          {
            id: 'gh76dnF7j3',
            title: 'Assign Task',
            primaryCondition: 'NO_TASKS',
            actions: [
              {
                operation: 'ASSIGN_TASK',
              },
            ],
            conditions: [
              {
                operation: 'TASKS_COUNT',
                sourceValue: 0,
              },
            ],
          },
        ]),
      );

    mock.verify();

    let query = new Parse.Query('_User');
    query.equalTo('objectId', userInst.id);
    let records = await query.find({ useMasterKey: true });
    expect(records[0].get('taskCount')).to.be.at.least(1); // max 10 tasks are assigned, but at least 1
    expect(records[0].get('taskCount')).to.not.be(100); // as defined while create user
  });

});

Мне в основном нужно смоделировать рабочий процесс, чтобы, если пользователь обновился, и их число задач было равно 0, тогда моя функция Parse Cloud afterSave запускает рабочий процесс NO_TASKS, если taskCount в этом пользователе 0 (который я обновляю для экземпляра пользователя).

Но я продолжаю получать:

  0 passing (1s)
  1 failing

  1) workflows
       workflow trigger
         should apply NO_TASKS workflow to user and increase their task count after its updated to 0:
     ExpectationError: Expected getFlowData(7QVfsilWx1, NO_TASKS[, ...]) at least once (never called)
Expectation met: getFlowData(7QVfsilWx1, USER_CREATED[, ...]) at least once
      at Object.fail (node_modules/sinon/lib/sinon/mock-expectation.js:281:25)
      at Object.verify (node_modules/sinon/lib/sinon/mock.js:108:29)
      at Context.<anonymous> (test/unit/workflow.js:3171:12)
      at processTicksAndRejections (internal/process/task_queues.js:93:5)

Таким образом, в основном ожидание первого вызова удовлетворено, но второе ожидание никогда не встречается.

...