expect方法读取wrapper.vm.shown的错误值

时间:2017-08-10 13:17:01

标签: javascript vue.js karma-runner avoriaz

我测试了我的组件,发生了一个非常奇怪的问题。

这是我的测试

import { mount } from 'avoriaz';


let wrapper = mount(MyComponent, { globals: {$route},});

it('the click changes the value of shown', () => {
    // This passes
    expect(wrapper.vm.shown).to.equal(false);

    // the click on this element will turn shown value into true
    wrapper.first('#my_link').trigger('click');

    // the value of shown is indeed true now
    console.log(wrapper.vm.shown); // LOG LOG: true

    expect(wrapper.vm.shown).to.equal(true); // expected undefined to equal true
});

shown作为参数传递给undefined方法时,expectconsole.log会发生什么?const recursivelyMapChildren = (node, index) => { return ( node.children.map((child, i) => { if (child.text) return child.text const tag = child.tag return React.createElement( tag, { key: `${tag}-${index}-${i}`, className: `text-block-${tag}`, ...child.attributes, }, recursivelyMapChildren(child, index + 1) ) }) ) } const STTextBlock = ({ data }) => { const textTag = data.content[0].tag return ( <div className="text-block"> { data.content.map(textBlock => React.createElement( textTag, { className: `${textTag}`, }, recursivelyMapChildren(textBlock) ) ) } <style jsx>{styles}</style> </div> ) } 时显示为布尔值?

1 个答案:

答案 0 :(得分:1)

第二次调用expect时,DOM尚未完成更新。

在调用expect之前使用$nextTick等待DOM更新:

wrapper.first('#my_link').trigger('click');

wrapper.vm.$nextTick(() => {
  expect(wrapper.vm.shown).to.equal(true);
});

使用异步代码时,console.log有时会懒惰地记录值,这意味着它们不会是您在该行执行时所期望的值。 See this post.