首页 > 解决方案 > sinon spy 检查是否调用了 func 总是返回 false 虽然函数

问题描述

我正在测试 javascript 应用程序,尽管该函数被称为函数总是抱怨它从未被调用。

这是代码片段和测试

test.spec.js

const Aupdate = require('../accountsUpdate');

it.only('should check if function is called or not', function(done) {
  let reqUpdateAccount = {
    body: {
      Account: 'newAccount1'
    }
  };
  let spy = sinon.spy(Aupdate, 'getUpdateArgs');
  Aupdate.accountsUpdate(reqUpdateAccount, res);
  expect(spy).to.have.been.called; //test fails
  done();
});

文件.js

function getUpdateArgs (Request) {
  console.log("func called);
 }

function accountsUpdate(req, res) {
 let args = getUpdateArgs(req.body);// function spied is called here
 ...
}


标签: javascriptunit-testingsinonsinon-chai

解决方案


这是解决方案:

index.ts

function getUpdateArgs(Request) {
  console.log('func called');
}

function accountsUpdate(req, res) {
  let args = exports.getUpdateArgs(req.body);
}

exports.getUpdateArgs = getUpdateArgs;
exports.accountsUpdate = accountsUpdate;

index.spec.ts

import { expect } from 'chai';
import sinon from 'sinon';

const Aupdate = require('./');

it.only('should check if function is called or not', function() {
  let reqUpdateAccount = {
    body: {
      Account: 'newAccount1'
    }
  };
  const res = {};
  let spy = sinon.spy(Aupdate, 'getUpdateArgs');
  Aupdate.accountsUpdate(reqUpdateAccount, res);
  expect(spy.calledWith({ Account: 'newAccount1' })).to.be.true;
  sinon.assert.calledOnce(spy);
});

单元测试结果:

func called
  ✓ should check if function is called or not

  1 passing (7ms)

源代码:https ://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57997682


推荐阅读