Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用practicalmeteor:mocha在Meteor的单元测试中伪造用户?_Javascript_Unit Testing_Meteor_Mocha.js - Fatal编程技术网

Javascript 如何使用practicalmeteor:mocha在Meteor的单元测试中伪造用户?

Javascript 如何使用practicalmeteor:mocha在Meteor的单元测试中伪造用户?,javascript,unit-testing,meteor,mocha.js,Javascript,Unit Testing,Meteor,Mocha.js,我很难在meteor中测试需要连接用户的方法。基本上,我需要测试应用程序的用户是否可以向其购物车添加文章。这些方法将测试用户是否已连接,为了测试,将使用Meteor.userId()。这似乎是单元测试中的一个问题,因为我得到了错误: “Meteor.userId只能在方法调用或发布中调用。” 到目前为止,我试着按照这篇文章的建议去做:但我不明白解决方案在做什么 以下是我的测试方法: import { Meteor } from 'meteor/meteor'; import { Random }

我很难在meteor中测试需要连接用户的方法。基本上,我需要测试应用程序的用户是否可以向其购物车添加文章。这些方法将测试用户是否已连接,为了测试,将使用Meteor.userId()。这似乎是单元测试中的一个问题,因为我得到了错误:
“Meteor.userId只能在方法调用或发布中调用。”

到目前为止,我试着按照这篇文章的建议去做:但我不明白解决方案在做什么

以下是我的测试方法:

import { Meteor } from 'meteor/meteor';
import { Random } from 'meteor/random';
import { assert } from 'meteor/practicalmeteor:chai';
import { sinon } from 'meteor/practicalmeteor:sinon';

import { Carts } from '/imports/api/carts/carts.js';
import { Articles } from '/imports/api/articles/articles.js';

import '/imports/api/carts/carts.methods.js';

import { SecurityEnsurer } from '/lib/security/security.js';

function randomInt (low, high) {
    return Math.floor(Math.random() * (high - low) + low);
}

if (Meteor.isServer) {
  describe('Carts', () => {
  describe('methods', () => {
    let currentUser;

    beforeEach(() => {
      Factory.define('user', Meteor.users, {
        name: "userTest",
        currentUser: {
          email: 'user@shop.info',
          password: '123456',
        }

      });

      currentUser = Factory.create('user');
      sinon.stub(Meteor, 'user');
      Meteor.user.returns(currentUser);

      Articles.remove({});

      articleId = Articles.insert({
        name : "azerty",
        description : "descTest",
        modelNumber : "wxcvbn",
        categoryName : "CatTest",
        price : 1,
        advisedPrice: 2,
        supplierDiscount : 0,
        brandId : "BrandTest",
        isAvailable: true,
        restockingTime: 42,
        color: "Yellow",
        technicals: [
          {
            name : "GPU",
            value : "Intel"
          },
        ],
      });

      Carts.insert({
        owner: currentUser,
        entries: [],
      });

    });

    afterEach(() => {
      Meteor.user.restore();
      Articles.remove({});
      Carts.remove({});
    });

    it('can add article', () => {
      let quantity = randomInt(1,50);

      const addArticleToCart = Meteor.server.method_handlers['carts.addArticle'];

      const invocation = {};

      addArticleToCart.apply(invocation, [articleId, quantity]);

      assert.equal(Cart.find({owner: currentUser, entries: {$elemMatch: {articleId, quantity}}}).count(), 1);
      });
    });
  }); 
}

如果有人能帮我找到如何创建我的测试,这对我真的很有帮助。

要在调用Meteor方法时伪造用户,我找到的唯一方法是使用
mdg:validated Method
包,该包提供了Meteor方法的框架。这个框架现在似乎是标准的(请参阅),但它需要重新编写方法和应用程序内调用

在描述了使用此框架的方法之后,您可以在测试时使用userId参数调用它们,使用此类代码(验证我的方法是否返回403错误):

仅供参考,以下是我在进行自动测试时添加的软件包(使用Meteor 1.6):


下面是我如何设置一个假登录用户来测试发布和方法:

1) 创建用户

2) 存根,即替换Meteor.user()和Meteor.userId()函数,这些函数返回当前登录的用户登录方法

3) 将该用户的_id提供给PublicationsCollector,后者会将其发送到您的发布功能中

我是这样做的,我希望你能从中适应:

import { Meteor } from 'meteor/meteor';
import { Factory } from 'meteor/dburles:factory';
import { PublicationCollector } from 'meteor/johanbrook:publication-collector';
import { resetDatabase } from 'meteor/xolvio:cleaner';
import faker from 'faker';
import { Random } from 'meteor/random';
import { chai, assert } from 'meteor/practicalmeteor:chai';
import sinon from 'sinon';
// and also import your publish and collection

Factory.define('user', Meteor.users, {
    'name': 'Josephine',
});

if (Meteor.isServer) {
    describe('Menus', () => {
        beforeEach(function () {
            resetDatabase();

            const currentUser = Factory.create('user');
            sinon.stub(Meteor, 'user');
            Meteor.user.returns(currentUser); // now Meteor.user() will return the user we just created

            sinon.stub(Meteor, 'userId');
            Meteor.userId.returns(currentUser._id); // needed in methods

            // and create a Menu object in the Menus collection
        });

        afterEach(() => {
            Meteor.user.restore();
            resetDatabase();
        });

        describe('publish', () => {
            it('can view menus', (done) => {
                const collector = new PublicationCollector({ 'userId': Meteor.user()._id }); // give publish a value for this.userId
                collector.collect(
                    'menus',
                    (collections) => {
                        assert.equal(collections.menus.length, 1);
                        done();
                    },
                );
            });
        });
    });
}
您还可以编写一个测试来调用依赖Meteor.userId()的Meteor方法:

meteortesting:mocha
dburles:factory
practicalmeteor:chai
johanbrook:publication-collector
import { Meteor } from 'meteor/meteor';
import { Factory } from 'meteor/dburles:factory';
import { PublicationCollector } from 'meteor/johanbrook:publication-collector';
import { resetDatabase } from 'meteor/xolvio:cleaner';
import faker from 'faker';
import { Random } from 'meteor/random';
import { chai, assert } from 'meteor/practicalmeteor:chai';
import sinon from 'sinon';
// and also import your publish and collection

Factory.define('user', Meteor.users, {
    'name': 'Josephine',
});

if (Meteor.isServer) {
    describe('Menus', () => {
        beforeEach(function () {
            resetDatabase();

            const currentUser = Factory.create('user');
            sinon.stub(Meteor, 'user');
            Meteor.user.returns(currentUser); // now Meteor.user() will return the user we just created

            sinon.stub(Meteor, 'userId');
            Meteor.userId.returns(currentUser._id); // needed in methods

            // and create a Menu object in the Menus collection
        });

        afterEach(() => {
            Meteor.user.restore();
            resetDatabase();
        });

        describe('publish', () => {
            it('can view menus', (done) => {
                const collector = new PublicationCollector({ 'userId': Meteor.user()._id }); // give publish a value for this.userId
                collector.collect(
                    'menus',
                    (collections) => {
                        assert.equal(collections.menus.length, 1);
                        done();
                    },
                );
            });
        });
    });
}
expect(() => { Meteor.call('myMethod'); }).to.not.throw(Meteor.Error);