标签: sinon

AngularJs测试Sinon间谍

我是Sinon的新手,所以我想检查一个特定的函数是否被调用,这就是我得到的:

terminalController.controller('CashAcceptorController', [
    'PaymentService',
    '$rootScope',
    '$scope',
    'PayingInfo',
    '$interval',
    '$location',
    function (PaymentService, $rootScope, $scope, PayingInfo, $interval, $location) {
     PaymentService.start();
....
]);
Run Code Online (Sandbox Code Playgroud)

在测试中,我尝试检查在控制器实例化上调用PaymentService.start():

describe('CashAcceptorController', function() {

var PaymentService, rootScope, scope, PayingInfo, $interval, $location;
var mySpy  = sinon.spy(PaymentService.start());;
beforeEach(module('eshtaPayTerminalApp.controllers'));

beforeEach(module('eshtaPayTerminalApp.services'));


beforeEach(inject(function($controller, 
        $rootScope, _PaymentService_, _$interval_, _PayingInfo_) {

    $interval = _$interval_;
    scope = $rootScope.$new();
    rootScope = $rootScope.$new();
    PaymentService = _PaymentService_;
    PayingInfo = _PayingInfo_;

    rootScope.serviceNumber = 'm1';
    rootScope.phoneNumber =  '05135309';

    $controller('CashAcceptorController', {
        $rootScope : rootScope,
        $scope : scope,
        $location : $location,
        _PaymentService_ : PaymentService,
        _$interval_:$interval,
        _PayingInfo_:PayingInfo …
Run Code Online (Sandbox Code Playgroud)

sinon angularjs

2
推荐指数
1
解决办法
2570
查看次数

我如何使 Sinon.JS callCount 递增

所以我有一个这样的 Chai/Mocha/Sinon 测试:

import sinon from 'sinon'

describe(`My Test`, () => {
  it(`should track the number of calls`, () => {
    function testMe() {
      console.log(`test me`)
    }
    const spy = sinon.spy(testMe)
    testMe()
    console.log(spy.getCalls())
    console.log(spy.callCount)
  })
})
Run Code Online (Sandbox Code Playgroud)

测试运行时,会记录以下内容:

test me
[]
0
Run Code Online (Sandbox Code Playgroud)

这令人费解。我究竟做错了什么?

javascript mocha.js sinon chai

2
推荐指数
1
解决办法
676
查看次数

如何使用 sinon.stub 编写单元测试以“请求”节点模块?

我的代码中有这个功能:

let request = require("request");
let getDrillDownData = function (userId, query, callback) {

query.id = userId;
let urlQuery = buildUrlFromQuery(query);

request.get({
    url: urlQuery,
    json: true
}, function (error, response, data) {
    if (!error && response.statusCode === 200) {
        return callback(null, calculateExtraData(data));
    } else if (error) {
        return callback(error, null);
    }
});


};
Run Code Online (Sandbox Code Playgroud)

我希望编写一些单元测试来验证当使用正确的参数调用函数时,它运行正常,如果出现错误,它确实返回了错误

我写了这个单元测试代码:

describe.only('Server Service Unit Test', function(){
var sinon = require('sinon'),
    rewire = require('rewire');

var reportService;
var reportData = require('./reportData.json');

beforeEach(function(){
    reportService = rewire('../../services/reports.server.service');
});

describe('report methods', function(){ …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing sinon angularjs

2
推荐指数
1
解决办法
1680
查看次数

使用Sinon的假定时器时不会触发setTimeout

我有一个类似于下面显示的测试.基本上我想测试特定方法是否会延迟.

以下示例按预期工作,即调用resolve方法并且测试通过:

it(`should delay execution by 1 second`, function () {
  const clock = sandbox.useFakeTimers();

  const p = new Promise(function (resolve) {
    setTimeout(resolve, 1000);
  });

  clock.tick(1000);

  return p;
});
Run Code Online (Sandbox Code Playgroud)

但是,如果我将setTimeout包装在另一个Promise中,则决不会调用该解析:

it(`should delay execution by 1 second`, function () {
  const clock = sandbox.useFakeTimers();

  const p = Promise.resolve()
    .then(() => {
      return new Promise(function (resolve) {
        setTimeout(resolve, 1000); // resolve never gets called
      });
    });

    clock.tick(1000);

    return p;
  });
Run Code Online (Sandbox Code Playgroud)

这有什么问题?

我正在使用Sinon 2.1.0和本地的承诺Node 6.9.5.

javascript settimeout node.js promise sinon

2
推荐指数
1
解决办法
2835
查看次数

如何使用 sinon 存根异步数据库调用

我正在尝试getAll对此类上的方法进行单元测试:

module.exports = class BookController {
  static async getAll() {
    return await Book.query()
      .eager('reviews');
  }
};
Run Code Online (Sandbox Code Playgroud)

Book 是一个异议模型。

我想如何测试它是我想Book.query().eager()用我自己的数据伪造响应,因为我永远无法验证数据库中的内容。要使其成为真正的单元测试,我是否应该只测试该Book.query()方法是否被调用?或者我应该测试返回的数据,因为这是getAll()方法的契约?我真的不确定我应该如何解决这个问题。

unit-testing mocha.js node.js sinon

2
推荐指数
1
解决办法
3856
查看次数

如何在摩卡咖啡中测试课程?

在迈向TDD的过程中,我正在使用Mocha,chai和sinon。那里肯定有学习曲线。

我的目标是编写一个测试来验证method4是否已执行。我该如何实现?

//MyData.js

 class MyData {

      constructor(input) {
         this._runMethod4 = input; //true or false
         this.underProcessing = this.init();
      }     

      method1() { return this.method2() }

      method2() {

        if (this._runMethod4) {
          return this.method4();
        } else {
         return this.method3();
       }

      method4(){
        return thirdPartyAPI.getData();
      }
      method3(){
        return someAPI.fetchData();
      }

      init(){
         return this.method1();
      }

    }
Run Code Online (Sandbox Code Playgroud)

MyData.spec.js

describe('MyData', () => {

  it('should execute method 4', function() {
      let foo = new MyData(true);

      foo.underProcessing.then(()=>{
       // How do I verify that method4 was executed ??
        expect(foo.method4.callCount).to.equal(1);
      });


   });
 })
Run Code Online (Sandbox Code Playgroud)

mocha.js sinon

2
推荐指数
1
解决办法
2689
查看次数

javascript 中的存根请求库

我正在使用第三方宁静服务发送短信验证码。我为它写了一个单元测试。但是,我不希望每次运行单元测试时都收到一条消息。

代码是这样的:

  const _request = require("request");

  _request({
  method: "POST",
  url: "http://blah.com/json",
  form: {
    apikey: "blah",
    mobile: input.mobilePhoneNumber,
    text: `code is: ${verificationCode}`,
  }
}, (err, res, body) => {
  if (err) {
    dbg(`end, output=${err}`)
    return reject(new Error("something wrong"))
  } else {
    dbg(`end, output=${res}`)
    return resolve({})
  }
})
Run Code Online (Sandbox Code Playgroud)

在测试中我使用 sinon.stub

sinon.stub(request, "post").returns(Promise.resolve({}))
Run Code Online (Sandbox Code Playgroud)

然而,这个存根并没有真正捕捉到请求中的“post”方法。我查看了源代码并尝试了很多方法(比如存根构造函数),但没有一个有效。

想知道有没有人以前试过这个。我应该如何根据要求存根这个 post 方法?

谢谢!

javascript unit-testing request mocha.js sinon

2
推荐指数
1
解决办法
558
查看次数

如何获取 sinon 中存根的参数并使用参数之一 + 其他数据作为特定存根调用的返回值

我想要实现的是存根一个将返回某个值的调用。该返回值由传递的参数之一和一个新值组成。

如何获取存根的参数并使用它来形成给定存根调用的返回值

例如

mockDb.query.onCall(0).return(
   Tuple(this.args(0), "Some other data");
);
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做:

sinon.stub(obj, "hello", function (a) {
    return a;
});
Run Code Online (Sandbox Code Playgroud)

但是,这适用于整个存根而不是单个存根调用。不幸的是,我无法为不同的调用提供不同的存根,因为我只有一个对象(db 存根)。

testing mocking node.js sinon chai

2
推荐指数
1
解决办法
4165
查看次数

组件单元测试中的模拟Vuex模块动作

我目前正在尝试模拟商店模块中的操作。我似乎无法正确地将其存根,因为我在单元测试中继续收到一条消息,内容是:

[vuex] unknown action type: moduleA/filterData
Run Code Online (Sandbox Code Playgroud)

这是被测组件的简化版本:

<template>
    <li class="list-item"
    @click="toggleActive()">
        {{ itemName }}
    </li>
</template>

<script>
import store from '../store'

export default {
    name: 'item',
    props: {
        itemName: {
            type: String
        }
    },
    data () {
        return {
            store,
            isActive: false
        }
    },

    methods: {
        toggleActive () {
            this.isActive = !this.isActive;
            this.$store.dispatch('moduleA/filterData', { name: itemName } );
        }
    }

}
</script>
Run Code Online (Sandbox Code Playgroud)

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import moduleA from './modules/moduleA'

Vue.use(Vuex)



const store = …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing sinon vue.js vuex

2
推荐指数
1
解决办法
1880
查看次数

ts-mockito-当参数是自定义对象时,存根方法不起作用

在我的其余架构中,有一个控制器(处理http请求)和一个服务(提供数据的业务逻辑)。

为了测试控制器,我试图对服务进行存根以提供固定的响应,但是我不明白如何对需要自定义对象作为参数的方法进行存根(如果该参数是文字,那么它将起作用)。

对于自定义对象(Farm),存根不起作用,因为并且我没有从服务方法中收到Promise,这是错误:

TypeError:无法在FarmsController.createFarm(/Users/giovannimarino/Projects/rt-cloud/services/farms/src/farms/farms.controller.ts:17:17)中读取null的'then'属性

farms.controller.spec.ts

describe('FarmsController', () => {
  const farmsServiceMock: FarmsService = mock(FarmsService);
  let controller: FarmsController;

  interface TestData {
    farm: Farm;
  }
  let testData: TestData;

  beforeEach(() => {
    reset(farmsServiceMock);
    const farmsServiceMockInstance: FarmsService = instance(farmsServiceMock);
    controller = new FarmsController(farmsServiceMockInstance);

    testData = {
      farm: <Farm> {
        name: 'CattD',
        imageUrl: 'img/farm-123b341.png',
        lang: 'en',
      }
    };
  });

  describe('createFarm function', () => {
    describe('success', () => {
      it('should return HTTP 200 OK', async () => {
        when(farmsServiceMock.createFarm(testData.farm)).thenReturn(Promise.resolve<Farm>(testData.farm));
        const pathParameters: PathParameter = {
          name: 'CattD', …
Run Code Online (Sandbox Code Playgroud)

unit-testing mocha.js sinon typescript

2
推荐指数
1
解决办法
1806
查看次数