Question d’entretien chez Cruise

Javascript Test driven coding: Make these unit tests pass by making code changes

Réponse à la question d'entretien

Utilisateur anonyme

15 juill. 2022

const Mocha = require('mocha') const assert = require('assert') const mocha = new Mocha() mocha.suite.emit('pre-require', this, 'solution', mocha) describe('Test suite', function() { it('should work', function() { assert(true) }) it('can create a store', () => { const store = createStore((state) => state); assert(typeof store.subscribe === 'function'); assert(typeof store.dispatch === 'function'); assert(typeof store.getState === 'function'); }); it('initializes with initial state', () => { const initialState = { foo: true, bar: false }; const store = createStore((state) => state, initialState); const state = store.getState(); assert(Object.keys(state).length === 2); assert(state.foo === true); assert(state.bar === false); }); it('can dispatch actions', () => { const reducer = (state, action) => { if (action.type !== 'SET_NAME') { return state; } return { ...state, name: action.payload, }; }; const store = createStore(reducer); console.log(store); store.dispatch({ type: 'FOO', payload: 'bar' }); assert(store.getState().name === undefined); store.dispatch({ type: 'SET_NAME', payload: 'foo' }); assert(store.getState().name === 'foo'); }); it('can subscribe and unsubscribe', () => { const reducer = (state, action) => { if (action.type !== 'SET_NAME') { return state; } return { ...state, name: action.payload, }; }; const store = createStore(reducer); let name = undefined; const unsubscribe = store.subscribe((state) => { name = state.name; unsubscribe(); }); assert(name === undefined); store.dispatch({ type: 'SET_NAME', payload: 'bar' }); assert(name === 'bar'); assert(store.getState().name === 'bar'); store.dispatch({ type: 'SET_NAME', payload: 'baz' }); assert(name === 'bar'); assert(store.getState().name === 'baz'); }); }) // YOUR CODE HERE function createStore(reducer) { let state = { foo: true, bar: false } return { subscribe: ()=>{}, getState: ()=>{ return state }, dispatch: (action)=>{ const obj = reducer(state, action) state.name = obj.name; }, } }; mocha.run()