在beforeEach中声明变量

时间:2018-05-29 08:57:07

标签: angular unit-testing const variable-declaration

我得到了

  

ReferenceError:未定义initialState

当我在beforeEach(()=> {...中将in​​itialState声明为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);
        });

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

这个问题确实很老,但是在这里为遇到这个问题的其他人提供一个有效的例子。这是您可以做到的一种方法:

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