【问题标题】:Declaring variable in beforeEach在 beforeEach 中声明变量
【发布时间】:2018-05-29 08:57:06
【问题描述】:

我明白了

ReferenceError: 未定义初始状态

当我在 beforeEach(()=> {... 中将 initialState 声明为 const 时。这不应该工作吗?

describe('register reducer', () => {
        beforeEach(() => {
            const initialState = UsersService.getInitialUsersState();
        })

        it('should return the initial state', () => {
            expect(usersReducer(undefined, [])).toEqual(initialState);
        });

        it('Toggle isBaby or sitter', () => {
            deepFreeze(initialState);
            let newState = initialState;
            newState.isBaby = true;

            expect(
                usersReducer(initialState, {
                    type: types.UsersActions.SET_TYPE,
                    payload: true
                })).toEqual(newState);
        });

【问题讨论】:

    标签: angular unit-testing constants variable-declaration


    【解决方案1】:

    这个问题真的很老了,但只是在这里为遇到这个问题的其他人提供一个工作示例。这是您可以做到的一种方法:

    describe('register reducer', () => {
      let initialState
      beforeEach(() => {
          initialState = UsersService.getInitialUsersState();
      })
    
      it('should return the initial state', () => {
          expect(usersReducer(undefined, [])).toEqual(initialState);
      });
    
      it('Toggle isBaby or sitter', () => {
          deepFreeze(initialState);
          let newState = initialState;
          newState.isBaby = true;
    
          expect(
            usersReducer(initialState, {
              type: types.UsersActions.SET_TYPE,
              payload: true
            })
          ).toEqual(newState)
      })
    })
    

    【讨论】:

      【解决方案2】:

      虽然beforeEach 确实在每次测试之前运行,但如果您这样做,initialState 仅在beforeEach 的范围内可见,请将其更改为:

      describe('register reducer', () => {
        let initialState;
        beforeEach(() => {
            initialState = UsersService.getInitialUsersState();
        })
        ...
      

      【讨论】:

      • 我明白了,但我也尝试了var,但它不起作用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-10
      • 2013-03-24
      • 2011-12-18
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多