我正在编写单元测试,以便组件在componentDidMount中获取所有用户的订单。在此之前,我检查会话是否超时或用户是否已登录,如果没有,请将它们重定向到登录页面。出于某种原因,我的测试似乎失败了。我如何断言这种情况?我的代码如下:
componentDidMount() {
this.checkCustomerCombinationState();
this.props.actions.getMyOrders();
}
checkCustomerCombinationState = () => {
if (TokenProvider.get('DP_USER_STATE') === '1' &&
(cookie.load('DP_USER_STATE') === '0')) {
TokenProvider.logout();
window.location.assign(constants.navigateToSessionTimeout.mobile);
}
}
以下是我的测试用例:
describe('Test Cases for the Orders component', () => {
let wrapper;
let cdmStub;
let TokenProviderGetStub;
let TokenProviderLogoutStub;
let CookieLoadStub;
// let pushStub = sinon.stub(browserHistory, 'push');
beforeEach(() => {
cdmStub = sinon.stub(Orders.prototype, 'componentDidMount');
TokenProviderGetStub = sinon.stub(TokenProvider, 'get');
TokenProviderLogoutStub = sinon.stub(TokenProvider, 'logout');
CookieLoadStub = sinon.stub(Cookie, 'load');
});
afterEach(() => {
TokenProviderGetStub.restore();
TokenProviderLogoutStub.restore();
CookieLoadStub.restore();
cdmStub.restore();
wrapper.unmount();
});
it('Initial State is set properly', () => {
wrapper = shallow(
<Orders {...props} />
);
expect(wrapper.state().ordersStartNumber).to.equal(0);
expect(wrapper.state().ordersEndNumber).to.equal(0);
});
it('MyOrders to be rendered', () => {
wrapper = shallow(
<Orders {...props} />
);
expect(wrapper.find('MyOrders').length).to.equal(1);
});
it('Correct props are passed to MyOrders', () => {
wrapper = shallow(
<Orders {...props} />
);
expect(wrapper.find('MyOrders').props().myOrders).to.deep.equal(ordersHistory.myOrders);
expect(wrapper.find('MyOrders').props().actions).to.deep.equal(actions);
});
describe('componentDidMount was called with session timedout', () => {
it('componentDidMount was called', () => {
wrapper = mount(
<Orders {...props} />
);
expect(cdmStub.calledOnce).to.be.true;
});
it('User is logged out if the session has ended', () => {
TokenProviderGetStub.withArgs('DP_USER_STATE').returns(1);
CookieLoadStub.withArgs('DP_USER_STATE').returns(0);
wrapper = mount(<Orders {...props} />)
expect(TokenProviderGetStub.called).to.be.true;
expect(CookieLoadStub.called).to.be.true;
expect(TokenProviderLogoutStub.called).to.be.true;
})
})
})
我的最后一次阻止失败了AssertionError: expected false to be true
。但是,它阻止componentDidMount was called
正在传递。我该如何解决这个问题?
答案 0 :(得分:0)
您需要等待组件安装。
it('User is logged out if the session has ended', async function(){
TokenProviderGetStub.withArgs('DP_USER_STATE').returns(1);
CookieLoadStub.withArgs('DP_USER_STATE').returns(0);
const mounted = await mount(<Orders {...props} />);
expect(TokenProviderGetStub.called).to.be.true;
expect(CookieLoadStub.called).to.be.true;
expect(TokenProviderLogoutStub.called).to.be.true;
})