测试一个函数使用Sinon.js在ES6模块中调用另一个函数 [英] Test that a function calls another function in an ES6 module with Sinon.js

查看:333
本文介绍了测试一个函数使用Sinon.js在ES6模块中调用另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试ES6模块中的一个函数使用Sinon.js调用另一个函数。这是我正在做的基本布局:

I want to test that a function in an ES6 module calls another function using Sinon.js. Here's the basic layout of what I'm doing:

foo.js

export function bar() {
 baz();
}

export function baz() {
 ...
}

test.js

import sinon from 'sinon';
import * as Foo from '.../foo';

describe('bar', function() {
  it('should call baz', function() {
    let spy = sinon.spy(Foo, 'baz');
    spy.callCount.should.eql(0);

    Foo.bar();

    spy.calledOnce.should.eql(true);
  });
}); 

但间谍不接电话给 baz()。还有其他方法我可以设置模块或测试,以允许sinon选择这个?我的替代方法是对某些baz做出一些基本的断言,但我显然不想这样做。

But the spy does not pick up the call to baz(). Is there some other way I can set up the module or the test to allow sinon to pick this up? My alternative is to make some basic assertion on something baz does, but I obviously don't want to be doing that.

从我在网上看到的是想知道这是否可以按原样排列,或者如果我需要重组以获得我想要的东西。

From what I've seen online I'm wondering if this is even possible with the code laid out as-is or if I need to restructure it to get what I want.

推荐答案

p>你是正确的,认为这是不可能的模块当前的结构的方式。

You're right in thinking this isn't possible with the way the module is currently structured.

代码执行时, baz 根据本地实现解决函数栏中的引用。您不能修改,因为模块代码以外的内部无法访问。

When the code is executed, the baz reference inside function bar is resolved against the local implementation. You can't modify that since outside of the module code there's no access to the internals.

您可以访问导出的属性,但是你不能突变这些,所以你不能影响模块。

You do have access to exported properties, but you can't mutate these and so you can't affect the module.

一种改变方式是使用这样的代码:

One way to change that is using code like this:

let obj = {};
obj.bar = function () {
 this.baz();
}

obj.baz = function() {
 ...
}

export default obj;

现在,如果您覆盖导入的 baz 对象你影响 bar 的内部。

Now if you override baz in the imported object you will affect the internals of bar.

说完了,感觉漂亮笨拙控制行为的其他方法存在,如依赖注入。

Having said that, that feels pretty clunky. Other methods of controlling behaviors exist such as dependency injection.

此外,您应该考虑是否真的关心 baz 被调用。在标准的黑箱测试中,您不关心如何完成某些操作,您只需要关心它产生的副作用。为此,测试您预期发生的副作用,没有其他任何事情完成。

Also, you should consider whether or not you actually care if baz was called. In standard "black-box testing", you don't care how something is done, you only care what side effects it generated. For that, test if the side effects you expected happened and that nothing else was done.

这篇关于测试一个函数使用Sinon.js在ES6模块中调用另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆