Redux의 "Reducer"는 기본적으로 초기 상태와 기본값을 반환 할 수 있습니까?

Antonio Pavicevac-Ortiz

저는 학교에서 Redux를 배우고 있습니다. 테스트를 통해 테스트를 통해 빌딩 블록을 이해하는 데 도움이되는 벤치 마크를 통과했습니다.

나는 내가 Reducer함수를 생성하는 부분에 달했고 거의 끝났지 \o/만 하나의 테스트를 통과 할 수 없습니다.

1) 기본적으로 초기 상태를 반환합니다.

그리고 콘솔 아래에서 다시 뱉어냅니다 ...

Reducer는 기본적으로 초기 상태를 반환합니다.

AssertionError : Context에서 undefined가 개체로 예상됩니다. (tests / redux.spec.js : 103 : 49)

내 생각에는 테스트가 예를 들어 가져 오기, 작업 유형 생성 등의 책임이있는 일부 문제를 처리하기 때문입니다. 그러나 전부는 아닙니다. 그렇다면 테스트에서 제공하지 않는 것이 누락되었을 수 있습니까?

어쨌든 여기 내 감속기 파일이 있습니다.

import pet from "../components/PetPreview";
import { createStore } from "redux";

import { adoptPet, previewPet, addNewDog, addNewCat } from "./action-creators";
// ACTION TYPES
const PREVIEW_PET = "PREVIEW_PET";
const ADOPT_PET = "ADOPT_PET";
const ADD_NEW_DOG = "ADD_NEW_DOG";
const ADD_NEW_CAT = "ADD_NEW_CAT";


// INTITIAL STATE
const initialState = {
  dogs: [
    {
      name: "Taylor",
      imgUrl: "src/img/taylor.png"
    },
    {
      name: "Reggie",
      imgUrl: "src/img/reggie.png"
    },
    {
      name: "Pandora",
      imgUrl: "src/img/pandora.png"
    }
  ],
  cats: [
    {
      name: "Earl",
      imgUrl: "src/img/earl.png"
    },
    {
      name: "Winnie",
      imgUrl: "src/img/winnie.png"
    },
    {
      name: "Fellini",
      imgUrl: "src/img/fellini.png"
    }
  ]
// These dogs and cats are on our intial state,
// but there are a few more things we need!
};


export default function reducer(prevState = initialState, action) {
  var newState = Object.assign({}, prevState)

  console.log('initialState', typeof initialState)
  switch (action.type) {

    case PREVIEW_PET:
      // console.log('newState', newState)
      return Object.assign({}, prevState, {
        petToPreview: action.pet
      });
      break
    case ADOPT_PET:
      return Object.assign({}, prevState, {
        petToAdopt: action.pet
      });
      break
    case ADD_NEW_DOG:
      // console.log('action', action.dog)
      // console.log('prevState.dogs', prevState.dogs)
      newState.dogs = prevState.dogs.concat([action.dog])
      return newState;
      break
    case ADD_NEW_CAT:
      // console.log('action', action.dog)
      // console.log('prevState.dogs', prevState.dogs)
      newState.cats = prevState.cats.concat([action.cat])
      return newState;
      break;
    default:
      return prevState;

  }
  return initialState
}

switch블록 이후에 볼 수 있듯이 내가 반환하고 initialState있습니다.

다음은 redux.spec.js파일입니다.

import { expect } from "chai";
import { createStore } from "redux";

// You will write these functions
import {
  previewPet,
  adoptPet,
  addNewDog,
  addNewCat
} from "../src/store/action-creators";
import reducer from "../src/store/reducer";

const DOGS = [
  {
    name: "Taylor",
    imgUrl: "src/img/taylor.png"
  },
  {
    name: "Reggie",
    imgUrl: "src/img/reggie.png"
  },
  {
    name: "Pandora",
    imgUrl: "src/img/pandora.png"
  }
];

const CATS = [
  {
    name: "Earl",
    imgUrl: "src/img/earl.png"
  },
  {
    name: "Winnie",
    imgUrl: "src/img/winnie.png"
  },
  {
    name: "Fellini",
    imgUrl: "src/img/fellini.png"
  }
];

function getRandomPet(pets) {
  return pets[Math.floor(Math.random() * pets.length)];
}

describe("Action creators", () => {
  describe("previewPet", () => {
    it("returns properly formatted action", () => {
      const pet = getRandomPet(DOGS);

      expect(previewPet(pet)).to.be.deep.equal({
        type: "PREVIEW_PET",
        pet: pet
      });
    });
  });

  describe("adoptPet", () => {
    it("returns properly formatted action", () => {
      const pet = getRandomPet(DOGS);

      expect(adoptPet(pet)).to.be.deep.equal({
        type: "ADOPT_PET",
        pet: pet
      });
    });
  });

  describe("addNewDog", () => {
    it("returns properly formatted action", () => {
      const pet = getRandomPet(DOGS);

      expect(addNewDog(pet)).to.be.deep.equal({
        type: "ADD_NEW_DOG",
        dog: pet
      });
    });
  });

  describe("addNewCat", () => {
    it("returns properly formatted action", () => {
      const pet = getRandomPet(CATS);

      expect(addNewCat(pet)).to.be.deep.equal({
        type: "ADD_NEW_CAT",
        cat: pet
      });
    });
  });
}); // end Action creators

describe("Reducer", () => {
  let store;

  beforeEach("Create the store", () => {
    // creates a store (for testing) using your (real) reducer
    store = createStore(reducer);
  });

  it("returns the initial state by default", () => {
    // In addition to dogs and cats, we need two more fields
    expect(store.getState().petToPreview).to.be.an("object");
    expect(store.getState().petToAdopt).to.be.an("object");
  });

  describe("reduces on PREVIEW_PET action", () => {
    it("sets the action's pet as the petToPreview on state (without mutating the previous state)", () => {
      const prevState = store.getState();

      const pet = getRandomPet(DOGS);
      const action = {
        type: "PREVIEW_PET",
        pet: pet
      };
      store.dispatch(action);

      const newState = store.getState();

      // ensures the state is updated properly - deep equality compares the values of two objects' key-value pairs
      expect(store.getState().petToPreview).to.be.deep.equal(pet);
      // ensures we didn't mutate anything - regular equality compares the location of the object in memory
      expect(newState.petToPreview).to.not.be.equal(prevState.petToPreview);
    });
  });

  describe("reduces on ADOPT_PET action", () => {
    it("sets the action's pet as the petToAdopt on state (without mutating the previous state)", () => {
      const prevState = store.getState();

      const pet = getRandomPet(DOGS);
      const action = {
        type: "ADOPT_PET",
        pet: pet
      };
      store.dispatch(action);

      const newState = store.getState();

      expect(newState.petToAdopt).to.be.deep.equal(pet);
      expect(newState.petToAdopt).to.not.be.equal(prevState.petToAdopt);
    });
  });

  describe("reduces on ADD_NEW_DOG action", () => {
    it("adds the new dog to the dogs array (without mutating the previous state)", () => {
      const prevState = store.getState();

      const pet = getRandomPet(DOGS);
      const action = {
        type: "ADD_NEW_DOG",
        dog: pet
      };
      store.dispatch(action);

      const newState = store.getState();

      expect(newState.dogs.length).to.be.equal(prevState.dogs.length + 1);
      expect(newState.dogs[newState.dogs.length - 1]).to.be.deep.equal(pet);
      expect(newState.dogs).to.not.be.equal(prevState.dogs);
    });
  });

  describe("reduces on ADD_NEW_CAT action", () => {
    it("adds the new cat to the cats array (without mutating the previous state)", () => {
      const prevState = store.getState();

      const pet = getRandomPet(CATS);
      const action = {
        type: "ADD_NEW_CAT",
        cat: pet
      };
      store.dispatch(action);

      const newState = store.getState();

      expect(newState.cats.length).to.be.equal(prevState.cats.length + 1);
      expect(newState.cats[newState.cats.length - 1]).to.be.deep.equal(pet);
      expect(newState.cats).to.not.be.equal(prevState.cats);
    });
  });

  describe("handles unrecognized actions", () => {
    it("returns the previous state", () => {
      const prevState = store.getState();

      const action = {
        type: "NOT_A_THING"
      };
      store.dispatch(action);

      const newState = store.getState();

      // these should be the same object in memory AND have equivalent key-value pairs
      expect(prevState).to.be.an("object");
      expect(newState).to.be.an("object");
      expect(newState).to.be.equal(prevState);
      expect(newState).to.be.deep.equal(prevState);
    });
  });
}); // end Reducer

미리 감사드립니다!

민다 잘 라즈

테스트 케이스에서 테스트 케이스 기본값 중 하나는

it("returns the initial state by default", () => {
    // In addition to dogs and cats, we need two more fields
    expect(store.getState().petToPreview).to.be.an("object");
    expect(store.getState().petToAdopt).to.be.an("object");
  });

즉, 초기 자체에서 상점에 연결된 petTpPreview 및 petToAdapt protery가 있어야합니다. 이것은 다음과 같이이 두 가지를 boject로 상태에 추가하여 수행 할 수 있습니다.

// INTITIAL STATE
const initialState = {
  petToPreview:{},
  petToAdopt: {},
  dogs: [
    {
      name: "Taylor",
      imgUrl: "src/img/taylor.png"
    },
    {
      name: "Reggie",
      imgUrl: "src/img/reggie.png"
    },
    {
      name: "Pandora",
      imgUrl: "src/img/pandora.png"
    }
  ],
  cats: [
    {
      name: "Earl",
      imgUrl: "src/img/earl.png"
    },
    {
      name: "Winnie",
      imgUrl: "src/img/winnie.png"
    },
    {
      name: "Fellini",
      imgUrl: "src/img/fellini.png"
    }
  ]
// These dogs and cats are on our intial state,
// but there are a few more things we need!
};

도움이 되길 바랍니다!

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

기본적으로 null이 아닌 반환 값을 지정하는 더 이상 사용되지 않는 기본 클래스 수준 주석이 있습니까?

매개 변수의 기본값을 함수의 반환으로 설정할 수 있습니까? (TCL)

Solarium은 기본적으로 requestHandler에서 제공하는 모든 패싯을 반환 할 수 있습니까?

반응 테이블의 firestore 값을 기반으로 확인란의 기본 상태를 어떻게 설정할 수 있습니까?

CouchDB는 기본적으로 일반 텍스트를 json 형식으로 변환 할 수 있습니까?

String & Number 인스턴스의 기본 값을 반환할 수 있습니까?

배열을 반환하는 함수의 결과로 useState에서 초기 상태를 어떻게 설정할 수 있습니까?

SAP의 웹 서비스는 기본적으로 사용할 수 있습니까?

초기 기본값에 대해 반응 상태에서 빈 개체를 제공할 수 있습니까?

'new'의 반환을 역 참조하는 값에서 참조를 초기화 할 수 있습니까?

값을 업데이트 할 수 없음 : 엔티티의 상태를 '수정 됨'으로 변경하는 동안 '기본 키'에 임시 값이 있습니다.

NFA와 DFA는 몇 개의 초기 상태를 가질 수 있습니까?

Camel-Hystrix-EIP : 교환중인 콘텐츠 본문을 기반으로 onFallback 또는 onFallbackViaNetwork를 동적으로 선택할 수 있습니까?

Excel에서 수식이 #NA를 반환하는 경우 "기본값"을 제공 할 수 있습니까?

상태 변경 후 감속기의 초기 상태를 변경하여 사용할 수 있습니까? 반응

Spring에서 @Value의 기본값으로 null을 설정할 수 있습니까?

ActiveSheet, ActiveWorkbook 또는 ThisWorkbook을 VBA의 선택적 매개 변수에 대한 기본값으로 어떻게 설정할 수 있습니까?

VBA 함수는 기본 하위에 값을 반환 할 수 없습니다.

동일한 직렬 변환기의 다른 필드 값을 기반으로 장고 REST 직렬 변환기의 속성 값을 초기화 할 수있는 방법이 있습니까?

함수 반환 값으로 std :: string 초기화, 복사본이 있습니까?

함수의 기본 반환 변수는 항상 할당됩니까?

꼬리와 머리의 기본 COUNT 값을 변경할 수 있습니까?

기본 함수가 자동을 반환 할 수 있습니까?

날짜가 기본적으로 ISO 8601 형식으로 결과를 반환하도록 할 수 있습니까?

"채널"유형의 필드는 "일반 유형으로 변수를 기본값으로 초기화 할 수 없음"오류를 제공합니다.

React + Redux에서 Props로 초기 상태를 설정할 수 있습니까?

반응 redux 감속기 상태에 있는 배열을 어떻게 필터링할 수 있습니까?

Redux의 초기 상태에서 localStorage를 사용할 수 있습니까, 아니면 사용해야합니까?

ReactJS가 서버 측 렌더링 된 DOM을 기반으로 상태를 초기화 할 수 있습니까?