标签: sinon

如何监视jQuery的追加函数Sinon

我试图用来sinon.js创建一个间谍jQuery.append功能.

我试过:var spy = sinon.spy($, "append");并得到以下错误: TypeError: Attempted to wrap undefined property append as function.

然后我修改为:var spy = sinon.spy($.fn, "append");看起来更好,但是spy.called错误.

javascript jquery sinon

3
推荐指数
1
解决办法
4023
查看次数

在 sinon 中“从头开始”创建一个假的 object.method()?

tl;博士

你如何在 sinon 中“从头开始”创建一个 object.method() ?

上下文

例如,我有一系列Parser类,其中每个类都实现一个#parse(text)方法并返回一个ParseTree对象或返回null.

我正在做单元测试,我测试Parser对象本身(它们在其他地方测试),但我需要一个响应#parse(). 我可以实例化并存根一个真正的解析器,但这会将不必要的代码拖入测试的这一部分。

问题

我很确定这很容易使用 sinon 的 spy()、stub() 和/或 mock() api,所以:我如何创建一个可测试的对象:

  • 响应 parse() 方法
  • 验证它被调用一次
  • 返回我指定的任意对象?

我试过的

以下人为示例在调用 时失败,sinon.stub()因为sinon.spy()无法使用parse方法存根对象。(此示例还应验证使用fake_parser.parse()调用了一次test_text,但它没有):

var test_text = 'any text'
var fake_parse_tree = sinon.spy()
var fake_parser = sinon.stub(sinon.spy(), 'parse').returns(fake_parse_tree)

expect(fake_parser.parse(test_text)).to.equal(fake_parse_tree)
Run Code Online (Sandbox Code Playgroud)

javascript mocha.js node.js sinon chai

3
推荐指数
1
解决办法
1215
查看次数

如何使用sinon对localStorage进行单元测试

我正在尝试localStorage使用sinon 进行测试.基本上我对单元测试很新,所以这可能是非常基础的.

更新

我设法提出这个,但现在它给了我一个新的错误 Should wrap property of object

测试

describe('Initial State', () => {
    it('should set the initial state for the component', () => {
const props = {
        currentUser: {}
      };
      sinon.stub(window.localStorage, 'setItem');
      window.localStorage.setItem('none', 'nothing');
    });
  });
Run Code Online (Sandbox Code Playgroud)

unit-testing sinon reactjs sinon-chai enzyme

3
推荐指数
2
解决办法
6090
查看次数

如何在 Sinon JS 的单元测试中处理 sinon.stub().throws()

我试图fail在我的代码段中调用条件。但是当我使用sinon.stub().throws()方法它显示我错误。我无法在代码中处理它。 这是我的片段:

login() {
    let loginData = this.loginData;
    return this.authService.login(loginData).then(userData => {

      let msg = `${this.niceToSeeYouAgain} ${userData.email}!`;
      this.userAlertsService.showSuccessToast(msg);
      this.navigationService.afterLoggedIn();

      //above lines are covered in test cases

    }, errorInfo => {
      // below line are needed to test
      this.userAlertsService.showAlertToast(errorInfo);
    });
}
Run Code Online (Sandbox Code Playgroud)

**这是我的单元测试片段:**

it('.login() - should throw exception - in failure case', sinon.test(() => {

    let errorInfo = "some error";

    let stub = sinon.stub(authService, 'login').throws();

    let spy1 = sinon.spy(controller.userAlertsService, 'showAlertToast');


    //call function
    controller.login();
    // $timeout.flush();

    // expect things …
Run Code Online (Sandbox Code Playgroud)

unit-testing sinon angularjs chai ecmascript-6

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

如何使用sinon.js存根https.request response.pipe?

假设我有以下简单代码:

var https = require('https');
var options = {
  host: 'openshift.redhat.com',
  port: 443,
  path: '/broker/rest/api',
  method: 'GET'
};
var req = https.request(options, function(response) {
  console.log(response.statusCode);
  response.pipe(save stream to file with fs)
});
req.on('error', function(e) {
  console.error(e);
});
req.end();
Run Code Online (Sandbox Code Playgroud)

好吧,我对sinon.js有点陌生,我想问一下:如何存入response.pipe()?当然,我可以对https.request进行存根处理并使用.on和.end返回某物很简单,但是我不知道如何测试response.pipe()是否使用适当的参数...(nodejs文档)说响应是回调),在这种情况下,文档无济于事!ofc testing env是mocha,也可以使用chai,请给我一些建议或示例。谢谢,马特

javascript unit-testing httprequest node.js sinon

3
推荐指数
1
解决办法
2633
查看次数

Sinon间谍功能被召唤但未被追踪

我正在使用Mocha和sinon监视函数调用.该函数被正确调用,但间谍没有跟踪它.

这是我正在测试的模块

export default (() => {

  function test1(){
      console.log('called second func');
      return 5;
  }

  function callThis(){
      console.log('called first func');
      test1();
  }

  return {
      test1,
      callThis
  };

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

这是测试

import Common from './common';

describe('spy test', () => {
  var setSpy = sinon.spy(Common, 'test1');

  Common.callThis();

  var result = setSpy.called;

  it(`does the test`, () => {
      expect(result).to.equal(true);
  });

});
Run Code Online (Sandbox Code Playgroud)

我基本上调用第一个函数,但想检查第二个函数被调用作为结果.控制台日志告诉我这种情况正在发生,但间谍返回false并且没有注意到它正在监视的事情.我错过了什么吗?

javascript mocha.js sinon

3
推荐指数
1
解决办法
712
查看次数

Sinon如何监视由Vue事件触发的Vue组件方法?

为了描述我的问题而进行的基本设置:

使用vue-cli 2.8.2,我基于webpack模板(vue init webpack vue-test-sinon-spy)生成了一个新项目,其中保留了vue-cli的所有默认值(禁用eslint无关)。

在此vue-cli生成的项目中所做的更改:

  1. 我在Hello.vue的h2标签上附加了一个事件:
<h2 @click="sayHello">Essential Links</h2>
Run Code Online (Sandbox Code Playgroud)
  1. 我在Hello组件中添加了一个方法
<script>
export default {
  ...
  methods: {
    sayHello() {
      console.log('hello!')
    }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)
  1. 我在Hello.spec.js中添加了一个新测试
describe('Hello.vue', () => {
  // ...

  it('should handle click on h2 tag', () => {
    const Constructor = Vue.extend(Hello)
    const vm = new Constructor().$mount()
    sinon.spy(vm, 'sayHello')

    // [A] if I run the line below, vm.sayHello.callCount will be 0 - not as expected
    vm.$el.querySelector('h2').click()

    // [B] if I run the line below, …
Run Code Online (Sandbox Code Playgroud)

sinon vuejs2

3
推荐指数
1
解决办法
3114
查看次数

如何检查是否使用sinon.useFakeTimers调用了clearTimeout?

我使用的是sinon伪造的计时器,我要检查,如果clearTimeout被称为具有特定的超时-ID.

var clock = sinon.useFakeTimers();
functionUnderTest();
// How can I know if functionUnderTest cleared a specific timeout?
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing sinon cleartimeout

3
推荐指数
1
解决办法
750
查看次数

为在JavaScript中使用jwt令牌的方法编写单元测试

我一直在尝试为使用jwt令牌验证的方法在javascript中编写单元测试。因此,仅当令牌有效时才获取结果。

我想模拟jwt令牌并返回结果。有什么办法吗?我尝试使用av​​a测试框架,mock require,sinon,但我做不到。

有什么想法吗 ?

码:

I am trying to mock jwt.verify    

**unit test:**

const promiseFn = Promise.resolve({ success: 'Token is valid' });

mock('jsonwebtoken', {
        verify: function () {         
            return promiseFn;   
        }
});

const jwt = require('jsonwebtoken');

const data =  jwt.verify(testToken,'testSecret');

console.log(data)


**Error :**

ERROR
    {"name":"JsonWebTokenError","message":"invalid token"} 


So the issue here is that, its actually verifying the token but not invoking the mock.
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing jwt sinon ava

3
推荐指数
1
解决办法
3299
查看次数

Sinon.js结合被调用次数

我知道使用sinon.js可以测试间谍被多次调用:

sinon.assert.calledTwice(mySpy.someMethod);
Run Code Online (Sandbox Code Playgroud)

您可以测试是否使用某些参数调用了间谍:

sinon.assert.calledWith(mySpy.someMethod, 1, 2);
Run Code Online (Sandbox Code Playgroud)

但是,如何将它们组合起来以测试某个方法被调用了特定次数的特定参数呢?理论上是这样的:

sinon.assert.calledTwiceWith(mySpy.someMethod, 1, 2);
Run Code Online (Sandbox Code Playgroud)

unit-testing sinon

3
推荐指数
1
解决办法
2110
查看次数