unt*_*mps 4 reactjs redux redux-saga
我创建了一个传奇,使用select从商店中检索一个值,并根据该值运行一条语句或另一条语句:
const {id} = action.payload;
try {
const cache = yield select(state => state.cache);
if (cache[id]) {
// Do something
} else {
// Do something else
} catch (e) {
// errors
}
Run Code Online (Sandbox Code Playgroud)
我试图用react-mock-store模拟商店:
import configureStore from 'redux-mock-store';
import createSagaMiddleware from 'redux-saga';
import { expect } from 'chai';
import { getCacheSaga } from '../../../src/js/sagas/cache-saga';
import { GET_CACHE } from '../../../src/js/actions/cache-actions';
const middlewares = [createSagaMiddleware()];
const mockStore = configureStore(middlewares);
mockStore({ cache: { foo: {} } });
describe('get cache saga', () => {
describe('getCacheSaga', () => {
it('retrieves data from cache', () => {
const iterator = getFormSaga({
payload: { id: 'foo' },
});
const cache = iterator.next();
console.log(cache); // undefined
});
});
Run Code Online (Sandbox Code Playgroud)
但这不起作用。有任何想法吗?
Sagas仅声明没有实际执行效果的效果。基本上这就是为什么可以完全不进行模拟测试的原因。
因此,您无需嘲笑任何东西。测试效果描述。
向您展示选择器
// cache-selector
export default state => state.cache
Run Code Online (Sandbox Code Playgroud)
内部测试
import getCache from './cache-selector'
describe('get cache saga', () => {
describe('getCacheSaga', () => {
it('retrieves data from cache', () => {
const iterator = getFormSaga({
payload: { id: 'foo' },
});
expect(iterator.next().value).to.be.deep.equal(select(getCache))
// fake effect
const fakeCache = { foo: 'bar'}
const nextEffect = iterator.next(fakeCache)
// next assertion
expect(nextEffect.value).to.be.deep.equal(...)
});
})
Run Code Online (Sandbox Code Playgroud)
长读
考虑以下示例
假设您需要测试执行以下操作的函数
function roll() {
if(Math.random() > 0.5) {
console.log('OK')
} else {
console.error('FAIL')
}
}
Run Code Online (Sandbox Code Playgroud)
如何测试呢?简单的答案就是嘲笑。在这里,你需要模拟Math.random,console.log,console.error
有了saga,您就可以不用嘲笑了。首先使用声明式效果进行重写
function* rollSaga() {
const random = yield call(Math.random)
if(random > 0.5) {
yield call(console.log, 'OK')
} else {
yield call(console.log, 'FAIL'
}
}
Run Code Online (Sandbox Code Playgroud)
然后测试
it('should call Math.random', () => {
const iter = rollSaga()
expect(iter.next().value).to.be.deep.equal(call(Math.random))
})
it('should log OK if random is > 0.5', () => {
const iter = rollSaga()
iter.next() // call random
expect(iter.next(0.6).value).to.be.deep.equal(call(console.log, 'OK'))
})
it('should show error if random is < 0.5', () => {
const iter = rollSaga()
iter.next() // call random
expect(iter.next(0.4).value).to.be.deep.equal(call(console.error, 'FAIL'))
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1480 次 |
| 最近记录: |