调试:状态改变时的奇怪问题

时间:2018-03-23 04:06:47

标签: reactjs unit-testing

我有一个奇怪的问题。

当我运行 Nav.test.js 时, fakeCountryCollection 也是 内部改变描述('别的'),为什么会这样?

我无法弄清楚我在哪里更改了fakeCountryCollection。

Nav.js

//clickNavDropdown will inverse showSubNav inside the state('countryCollection');

clickNavDropdown(countryCounter){
    let countryCollection = this.state.countryCollection;
    countryCollection[countryCounter].showSubNav = !countryCollection[countryCounter].showSubNav;

    this.setState({'countryCollection':countryCollection});
}

Nav.test.js

describe('test nav.js', function () {

    let fakeCountryCollection = [{value: 'england', count: 2, showSubNav: true},
        {value: 'canada', count: 0, showSubNav: false},
        {value: 'thailand', count: 0, showSubNav: true},
        {value: 'hongkon', count: 0, showSubNav: true}];


//clickNavDropdown will inverse showSubNav inside the state('countryCollection'). 
    describe('function clickNavDropdown', function () {
        let app = shallow(<Nav/>);
        app.setState({'countryCollection': fakeCountryCollection});
        let countryCollection = app.state('countryCollection');

        for (let [index, eachCollection] of countryCollection.entries()) {       

            app.instance().clickNavDropdown(index);
            it('iterator the countryCollection in: '+index, function () {
                ...
            });
        }
    });

    describe('something else', function () {
        console.log('fakeCountryCollection been inverse:  ',fakeCountryCollection);
        ...
    });
});

关注终端中的节目:

 fakeCountryCollection been inverse:   
      [ 
           { value: 'england', count: 2,showSubNav: false },
           { value: 'canada', count: 0, showSubNav: true },
           { value: 'thailand', count: 0, showSubNav: false },
           { value: 'hongkon', count: 0, showSubNav: false }
      ]

1 个答案:

答案 0 :(得分:0)

我无法肯定地说,因为Nav.test.js的代码片段有遗漏,但看起来你正在改变fakeCountryCollection。

将它声明为const,如果有错误,它应该告诉你你在哪里做了不想要的变异。