簡體   English   中英

如何使用Jest在ES6類方法中測試對redux存儲的調度?

[英]How can I test a dispatch to a redux store in an ES6 class method with Jest?

我嘗試測試是否在ES6類方法內發生了對redux存儲的調度,但是我失敗了。

我以某種方式無法找到如何模擬商店以獲取響應的方法。

方法很簡單:

class Foo {
  …
  bar() {
    store.dispatch({ type: FOO_BAR_BAZ });
  }
  …
};

我只想測試調度是否已發生。

我嘗試了一些操作,包括redux-mock-store ,但沒有收到該商店的反饋。

it('should foo bar baz', () => {
  const store = {
    dispatch: jest.fn(),
  };

  const foobar = new Foo();
  foobar.bar();

  console.log(store.dispatch.mock);
  //=> { calls: [], instances: [], invocationCallOrder: [], results: [] }
});

如果有人能指出正確的方向,我將深表感謝。

不能調用Jest store模擬,因為該類無權訪問它。 解決此問題的一種方法是將存儲傳遞給構造函數:

class Foo {
  constructor(store) {
    this.store = store
  }

  bar() {
    this.store.dispatch({ type: FOO_BAR_BAZ });
  }
}

-

it('should foo bar baz', () => {
  const store = {
    dispatch: jest.fn(),
  };

  const foobar = new Foo(store);
  foobar.bar();

  console.log(store.dispatch.mock);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM