如何使用 Jest 在 ES6 class 方法中测试对 redux 存储的调度?
How can I test a dispatch to a redux store in an ES6 class method with Jest?
我尝试测试在 ES6 class 方法中是否发生了对 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: [] }
});
如果有人能指出正确的方向,我将不胜感激。
未调用笑话 store
模拟,因为 class 无权访问它。解决这个问题的一种方法是将商店传递给构造函数:
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);
});
我尝试测试在 ES6 class 方法中是否发生了对 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: [] }
});
如果有人能指出正确的方向,我将不胜感激。
未调用笑话 store
模拟,因为 class 无权访问它。解决这个问题的一种方法是将商店传递给构造函数:
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);
});