【问题标题】:Ngrx unit test jasmine reducer how to compare stateNgrx单元测试茉莉减速器如何比较状态
【发布时间】:2020-08-28 12:38:45
【问题描述】:

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

// 模拟

    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 测试结果?

【问题讨论】:

    标签: jasmine ngrx


    【解决方案1】:

    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);
        });
      });
    });
    

    【讨论】:

    • 感谢您的帮助,但这个 expect(actualState).toEqual(expectedState);由于递归对象而无法工作
    • 您可以将减速器和初始状态添加到问题中吗?
    • 我认为对于每个测试,您都需要创建自己的初始状态,而不是使用全局状态。
    • 我没有看到任何递归。你的意思是因为tokenauth?这正是toEqual 所做的——它检查对象的所有节点以确保键和它们的值是相同的,即使它们是深度嵌套的。你可以在这里发布你得到的错误吗?
    • 我已经更新了代码 - 现在这个测试应该适用于您的数据。
    猜你喜欢
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    相关资源
    最近更新 更多