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
}
私は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
});
});
しかし、それは機能しません。何か案は?
Sagasは、実際に効果を実行せずに効果を宣言するだけです。それが基本的に、モックなしでテストできる理由です。
したがって、何もモックする必要はありません。テスト効果の説明。
セレクターを公開する
// cache-selector
export default state => state.cache
内部テスト
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(...)
});
})
ロングリード
次の例を考えてみましょう
次のことを行う関数をテストする必要があるとします。
function roll() {
if(Math.random() > 0.5) {
console.log('OK')
} else {
console.error('FAIL')
}
}
それをテストする方法は?簡単な答えはあざけることでしょう。そして、ここであなたがモックする必要がありますMath.random
、console.log
、console.error
佐賀では、モックなしでそれを行うことができます。宣言型効果を使用して最初に書き直す
function* rollSaga() {
const random = yield call(Math.random)
if(random > 0.5) {
yield call(console.log, 'OK')
} else {
yield call(console.log, 'FAIL'
}
}
次にテストします
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'))
})
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加