javascript - 无法使用 Sinon stub 函数

标签 javascript redux sinon

我有一个 Redux 操作,它本身会分派(dispatch)另外两个操作。每个 Action 都是从导入的函数中检索的。一个来自本地模块,另一个来自外部库。

import { functionA } from './moduleA';
import { functionB } from 'libraryB';

export function myAction() {
  return (dispatch) => {
    dispatch(functionA());
    ...
    dispatch(functionB());
  }
}

在我的测试中,我使用的是 sinon沙箱来 stub 函数,但只有两个测试通过。我希望这三个都能通过。
import * as A from './moduleA';
import * as B from 'libraryB';

describe(__filename, async () => {
  it('Calls 2 other actions', () => {
    sandbox = sinon.sandbox.create();

    const dispatch = sandbox.stub();

    sandbox.stub(A, 'functionA');
    sandbox.stub(B, 'functionB');

    await myAction()(dispatch);

    // passes
    expect(dispatch.callCount).to.equal(2);

    //passes
    expect(A.functionA).to.have.been.called();

    // fails
    expect(B.functionB).to.have.been.called();     
  });
});

最后一个期望因错误而失败:

TypeError: [Function: functionB] is not a spy or a call to a spy!



当我将函数输出到控制台时,我得到了这个,这似乎与 Babel 导入导出导出的方式有关
(ES6 re-exported values are wrapped into Getter)。这些功能可以实时工作,而不是在测试中。
{ functionA: [Function: functionA] }
{ functionB: [Getter] }

我试过使用 stub.get(getterFn) 但这只是给了我错误:

TypeError: Cannot redefine property: fetchTopicAnnotations

最佳答案

你试过命名你的 stub 吗?你的代码读起来有点奇怪。您在测试中的任何时候都没有提到您的 stub 。

import * as A from './moduleA';
import * as B from 'libraryB';

describe(__filename, async () => {
  it('Calls 2 other actions', () => {
    sandbox = sinon.sandbox.create();

    const dispatch = sandbox.stub();

    const functionAStub = sandbox.stub(A, 'functionA');
    const functionBStub = sandbox.stub(B, 'functionB');

    await myAction()(dispatch);

    // passes
    expect(dispatch.callCount).to.equal(2);

    //passes
    expect(functionAStub.called).toBe(true);

    // fails
    expect(functionBStub.called).toBe(true);     
  });
});

关于javascript - 无法使用 Sinon stub 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46361748/

相关文章:

javascript - 元素文本更改时的过渡高度

javascript - 如何使用 javascript 从 HTML 选择选项 onchange 中发布 PHP 变量?

react-native - 将 socket.io 与 redux reducer 相结合

node.js - Sinon 函数 stub : How to call "own" function inside module

node.js - 具有异步回调的单元测试快速路由

javascript - ckeditor 中的图像上传弹出窗口在 Google Chrome 中不起作用

javascript - XMLHttpRequest - Chrome 和 Firefox 之间的区别

javascript - 将 redux saga 负载传递给另一个操作的正确方法

node.js - 使用 Sinon、redux 和 Karma 测试 axios 调用

node.js - 为什么我的 Sinon spy 函数在 promise then 子句中调用时不起作用?