Ngrx单元测试jasmine reducer如何比较状态

Ngrx unit test jasmine reducer how to compare state

我已经完成了这个简单的测试

// 模拟

    const loginResponseData: LoginResponseDto = {
      auth: { id: 1, username: 'me', roles: [] },
      token: {
        token: 'abc',
        expirationEpochSeconds: 12345
      }
    };
    describe('AuthReducer', () => {
      describe('loginSuccess', () => {
        it('should show loginResponseData state', () => {
          const createAction = loginSuccess({ payload: loginResponseData });

          const result = reducer(initialState, createAction);
          console.log('AUTH', result);
          // How Can I test this?
          //expect(result).toEqual(loginResponseData);
        });
      });
    });
export const initialState: State = {
  error: null,
  loading: false,
  registered: false,
  payload: null
};
const authReducer = createReducer(
  initialState,
  on(AuthActions.loginSuccess, (state, { payload }) => {
    return {
      ...state,
      error: null,
      loading: false,
      payload
    };
  })
);

如何使用 loginResponseData 测试结果?

reducer 的结果是一个新的状态。 您需要共享您的减速器代码以获得正确答案。或者分享 console.log 的输出。

因为你问题中的代码是正确的

describe('AuthReducer', () => {
  describe('loginSuccess', () => {
    it('should show loginResponseData state', () => {

      const actionPayload: LoginResponseDto = {
        auth: { id: 1, username: 'me', roles: [] },
        token: {
          token: 'abc',
          expirationEpochSeconds: 12345
        }
      };

      // for the test it's fine to have an empty object
      const initialState: any = {
      };

      // check what should be changed
      const expectedState = {
        payload: {
          auth: { id: 1, username: 'me', roles: [] },
          token: {
            token: 'abc',
            expirationEpochSeconds: 12345
          },
        },
        error: null,
        loading: false,
      };

      const createAction = loginSuccess({ payload: loginResponseData });

      // returns updated state we should compare against expected one.
      const actualState = reducer(initialState, createAction);

      // assertions
      expect(actualState).toEqual(expectedState);
    });
  });
});