首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用spy和sinon js

使用spy和sinon js
EN

Stack Overflow用户
提问于 2017-01-24 16:47:45
回答 1查看 333关注 0票数 1

我有以下函数

代码语言:javascript
复制
function trim(value) {
  if (typeof value === 'string') {
    if (String.prototype.trim) {
      value = value.trim();
    } else {
      value = value.replace(/^\s+|\s+$/g, '');
    }

    return value;
  }
} 

我正在为它编写一个单元测试,以确保在调用trim时,如果可用,也会调用本机String.prototype.trim。我正在尝试使用spy来确保它被调用

代码语言:javascript
复制
var Util = require('test/util/methods');

it('should use native trim', function() {
    var spy = sinon.spy(String.prototype, 'trim');
    Util.trim('test string   ');
    expect(spy.calledOnce).toEqual(true);
    expect(Util.trim('test string    ')).toEqual('test string');
    spy.restore();
  });

但我觉得我应该做的是,当trim被调用时,我应该检查String.prototype.trim也被调用了。

我该怎么做呢?如果任何人有任何指示,请也建议,因为我想得到它的测试方面,我可以尽我所能

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-24 16:57:13

所以只调用trim一次,然后使用两个expect

代码语言:javascript
复制
it('should use native trim', function() {
    var spy = sinon.spy(String.prototype, 'trim');
    expect(Util.trim('test string    ')).toEqual('test string');
    expect(spy.calledOnce).toEqual(true);
    spy.restore();
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41823661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档