【问题标题】:Meteor & Mocha Chai : test insert functionMeteor & Mocha Chai : 测试插入函数
【发布时间】:2017-02-14 22:23:42
【问题描述】:

我正在尝试测试我的插入功能,但它因 UserAccount 失败:错误:无法读取未定义的属性“用户名”

我不知道如何使插入帖子的测试通过,这是我的方法:

Meteor.methods({

  'posts.insert'(title, content) {
     check(title, String);
     check(content, String);


     if (! this.userId) {
         throw new Meteor.Error('not-authorized');
     }

     const urlSlug = getSlug(title);

     Posts.insert({
        title,
        content,
        urlSlug,
        createdAt: new Date(),
        owner: this.userId,
        username: Meteor.users.findOne(this.userId).username,
     });
  },

});

这是我要测试的测试方法:

if (Meteor.isServer) {
    describe('Posts', () => {
        describe('methods', () => {
            const userId = Random.id();
            let postId;

            beforeEach(() => {
                Posts.remove({});

                postId = Posts.insert({
                    title: 'test post',
                    content: 'test content',
                    urlSlug: 'test-post',
                    createdAt: new Date(),
                    owner: userId,
                    username: 'toto',
                });
            });

            // TEST INSERT METHOD
            it('can insert post', () => {
                const title = "test blog 2";
                const content = "test content blog 2";

                const insertPost Meteor.server.method_handlers['posts.insert'];
                const invocation = { userId };
                insertPost.apply(invocation, [title, content]);
                assert.equal(Posts.find().count(), 2);
            });
       });
   });
 }

你能帮帮我吗?

【问题讨论】:

    标签: javascript reactjs meteor mocha.js karma-mocha


    【解决方案1】:

    使用sinon stub 流星调用怎么样?虽然我不确定它是否适用于嵌套对象(如果有人可以确认的话)。

    sinon.stub(Meteor, 'users.findOne').returns({ username: 'Foo' });
    

    并且不要忘记在使用后恢复它(例如afterEach())。

    Meteor.users.findOne.restore();
    

    【讨论】:

    • sinon.stub(Meteor.users, 'findOne').returns({ username: 'Foo' }); 是正确的方法。我在上面尝试过,但遇到了一些关于它不是属性的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多