小编Mih*_*šič的帖子

如何用jest和酶模拟React组件方法

我有一个反应组件(这是为了证明问题而简化):

class MyComponent extends Component {
    handleNameInput = (value) => {
        this.searchDish(value);
    };

    searchDish = (value) => {
      //Do something
    }

    render() {
        return(<div></div>)
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想用提供的值测试那些handleNameInput()调用searchDish.

为了做到这一点,我想创建一个替换组件方法的jest模拟函数.

到目前为止,这是我的测试用例:

it('handleNameInput', () => {
   let wrapper = shallow(<MyComponent/>);
   wrapper.searchDish = jest.fn();
   wrapper.instance().handleNameInput('BoB');
   expect(wrapper.searchDish).toBeCalledWith('BoB');
})
Run Code Online (Sandbox Code Playgroud)

但是我在控制台中获得的是SyntaxError:

的SyntaxError

  at XMLHttpRequest.open (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:458:15)
  at run_xhr (node_modules/browser-request/index.js:215:7)
  at request (node_modules/browser-request/index.js:179:10)
  at DishAdmin._this.searchDish (src/main/react/components/DishAdmin.js:155:68)
  at DishAdmin._this.handleNameInput (src/main/react/components/DishAdmin.js:94:45)
  at Object.<anonymous> (src/main/react/tests/DishAdmin.test.js:122:24)
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,如何用酶正确模拟组分方法?

javascript reactjs jestjs enzyme

48
推荐指数
2
解决办法
5万
查看次数

jest:测试套件无法运行,SyntaxError:意外的令牌导入

这是我在package.json文件中的jest配置:

"jest": {
    "automock": false,
    "browser": true,
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "./app/tests/mocks/FileMock.js",
      "\\.(css|less)$": "identity-obj-proxy"
    },
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleDirectories": [
      "node_modules"
    ],
    "transform": {
      "^.+\\.jsx?$": "./node_modules/babel-jest",
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "./app/tests/mocks/FileTransformer.js"
    },
    "testEnvironment": "jsdom",
    "testPathDirs": [
      "./app/tests"
    ],
    "testRegex": ".*.test.js",
    "verbose": true
  }
Run Code Online (Sandbox Code Playgroud)

和.babelrc文件位于我的根文件夹中:

{
  "plugins": ["syntax-dynamic-import", "transform-runtime"],
  "presets": [
    [
      "es2015",
      {
        "modules": false
      }
    ],
    "react",
    "stage-0"
  ],
  "env": {
    "start": {
      "presets": [
        "react-hmre"
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

根据在开玩笑的入门页面上找到的文档,这是我需要让babel工作的所有东西.

无论如何,这个测试:

import React from 'react';
import …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs babeljs

43
推荐指数
4
解决办法
5万
查看次数

AngularJS错误.success不是函数

我已经构建了一个工厂来处理我的控制器的功能,但不知何故控制器在其中一个函数上返回错误:

错误:Auth.getUser(...).成功不是函数@ http:// localhost:8080/app/controllers/mainCtrl.js:10:1
...

我不知道这里发生了什么,其余的功能似乎工作得很好?

主控制器:

angular.module('mainCtrl', [])
.controller('mainController', function($rootScope, $location, Auth) {
    var vm = this;
    vm.loggedIn = Auth.isLoggedIn();
    $rootScope.$on('$routeChangeStart', function() {
        vm.loggedIn = Auth.isLoggedIn();
        Auth.getUser()
            .success(function(data) {
                vm.user = data;
            });
    });
    vm.doLogin = function() {
        Auth.login(vm.loginData.username, vm.loginData.password)
            .success(function(data) {
                $location.path('/users');
            });
    };
});
Run Code Online (Sandbox Code Playgroud)

angularjs

34
推荐指数
2
解决办法
6万
查看次数

Angular2 - 将[_ngcontent-mav-x]添加到样式中

我正在设置一个基本的角度应用程序,我正在尝试为我的观点注入一些CSS.这是我的一个组件的示例:

import { Component } from 'angular2/core';
import { ROUTER_PROVIDERS, ROUTER_DIRECTIVES, RouteConfig } from 'angular2/router';

import { LandingComponent } from './landing.component';
import { PortfolioComponent } from './portfolio.component';

@Component({
    selector: 'portfolio-app',
    templateUrl: '/app/views/template.html',
    styleUrls: ['../app/styles/template.css'],
    directives: [ROUTER_DIRECTIVES],
    providers: [ROUTER_PROVIDERS]
})

@RouteConfig([
    { path: '/landing', name: 'Landing', component: LandingComponent, useAsDefault: true },
    { path: '/portfolio', name: 'Portfolio', component: PortfolioComponent }
])

export class AppComponent { }
Run Code Online (Sandbox Code Playgroud)

现在从我的服务器请求.css文件,当我检查页面源时,我可以看到它被添加到头部.但是发生了一些奇怪的事情:

<style>@media (min-width: 768px) {


    .outer[_ngcontent-mav-3] {
        display: table;
        position: absolute;
        height: 100%;
        width: 100%;
    } …
Run Code Online (Sandbox Code Playgroud)

css typescript angular

27
推荐指数
2
解决办法
2万
查看次数

Yeoman和Bower没有添加Bootstrap CSS(AngularJS生成器)

我沿着以下代码实验室对约曼网页,到目前为止,我已经成功地跟着一起(有以下几个主要打嗝让我的开发环境中去,但现在它不返回任何错误).

所以我制作了我的项目文件夹并运行yo,选择了AngularJS并运行该东西.很快进入这个过程我得到了一个提示,? Overwrite package.json?y得到了以下警告:

npm WARN package.json codelab@0.0.0 No license field.
npm WARN peerDependencies The peer dependency karma@>=0.9 included from karma-jasmine will no
npm WARN peerDependencies longer be automatically installed to fulfill the peerDependency 
npm WARN peerDependencies in npm 3+. Your application will need to depend on it explicitly.
npm WARN peerDependencies The peer dependency jasmine-core@* included from karma-jasmine will no
npm WARN peerDependencies longer be automatically installed to fulfill the peerDependency …
Run Code Online (Sandbox Code Playgroud)

twitter-bootstrap angularjs yeoman bower yeoman-generator-angular

26
推荐指数
3
解决办法
1万
查看次数

刷新页面时,Angular2不会注入模板CSS

我有一个使用选择器的应用程序,portfolio-app有2个样式表 -'../app/styles/templateMobile.css', '../app/styles/templateOther.css'

现在,当我从默认URL(localhost:3000 ATM)打开我的应用程序时,样式表正确应用.但是当我转到其他路线并按下刷新(F5)时,模板样式不会应用于页面.当我开始不同的路线时,会发生同样的事情.

控制台中没有错误消息.

我在firefox,chrome和safari,隐身模式以及清除浏览器缓存中测试了这个.我还测试了LG G2,iPhone,iPad和各种Android模拟器(Nexus 9,Nexus 10,Galaxy Nexus).结果总是一样的.

app.component:

import { Component } from 'angular2/core';
import {ViewEncapsulation} from 'angular2/core';
import { ROUTER_PROVIDERS, ROUTER_DIRECTIVES, RouteConfig } from 'angular2/router';

import { LandingComponent } from './landing.component';
import { PortfolioComponent } from './portfolio.component';
import { PagesService } from './pages.service';

@Component({
    selector: 'portfolio-app',
    templateUrl: '/app/views/template.html',
    styleUrls: ['../app/styles/templateMobile.css', '../app/styles/templateOther.css'],
    encapsulation: ViewEncapsulation.None,
    directives: [ROUTER_DIRECTIVES],
    providers: [ROUTER_PROVIDERS, PagesService]
})

@RouteConfig([
    { path: '/landing', name: 'Landing', component: LandingComponent, useAsDefault: true },
    { path: …
Run Code Online (Sandbox Code Playgroud)

css typescript angular

13
推荐指数
1
解决办法
5536
查看次数

Angular2 - OnInit未定义

我正在尝试实现angular 2 onInit函数,但我在控制台中收到以下错误:

错误:ReferenceError:未定义OnInit(...)

有人可以指出我做错了什么吗?

这是我的组成部分:

import { Component, OnInit } from 'angular2/core';
import { ViewEncapsulation } from 'angular2/core';

@Component({
    selector: 'Landing',
    templateUrl: '/app/views/landing.html',
    styleUrls: ['../app/styles/landing.css'],
    encapsulation: ViewEncapsulation.None
})

export class LandingComponent implements OnInit {

    function checkOverflow() {
        var element = document.querySelector('.appContainer');
        if( (element.offsetHeight < element.scrollHeight) || (element.offsetWidth < element.scrollWidth)){
           // your element have overflow
          console.log('OVERFLOW!');
        }
        else{
          console.log('NO OVERFLOW');
        }
    }

    OnInit() {
        checkOverflow();
    }

}
Run Code Online (Sandbox Code Playgroud)

typescript angular

12
推荐指数
1
解决办法
1万
查看次数

如何获取数组的每个第3个元素

我有一个数组,并希望只返回每个第三个元素作为一个新数组(从0开始).

例如:

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let newArr = [1, 4, 7];
Run Code Online (Sandbox Code Playgroud)

这是我目前这样做的方式:

let newArr = [];
for(let x = 0; x < arr.length; x += 3) {
   newArr.push(arr[x]);
}
return newArr;
Run Code Online (Sandbox Code Playgroud)

有没有办法用arr.map做到这一点?有没有更简单的方法来做到这一点?

javascript arrays

10
推荐指数
1
解决办法
4735
查看次数

jest,enzyme - 测试返回jsx的方法

我有以下组件:

import React, { Component } from 'react';
import {Link, IndexLink} from 'react-router';

class Navbar extends Component {

  renderLinks = (linksData) => {
    return linksData.map((linkData) => {
      if(linkData.to === '/') {
        return(
          <div className="navbar-link-container" key={linkData.to}>
            <IndexLink activeClassName="navbar-active-link" to={linkData.to}>
              <i className="navbar-icon material-icons">{linkData.icon}</i>
              <span className="navbar-link-text">{linkData.text}</span>
            </IndexLink>
          </div>
        )
      }
      else {
        return(
          <div className="navbar-link-container" key={linkData.to}>
            <Link activeClassName="navbar-active-link" to={linkData.to}>
              <i className="navbar-icon material-icons">{linkData.icon}</i>
              <span className="navbar-link-text">{linkData.text}</span>
            </Link>
          </div>
        )
      }
    })
  };

  render() {
    return (
      <div className={`navbar navbar-${this.props.linksData.length}`}>
        {this.renderLinks(this.props.linksData)}
      </div>
    )
  }
}

Navbar.propTypes …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs enzyme

10
推荐指数
3
解决办法
9538
查看次数

Windows 10 - 具有空格和PATH的用户名

安装Windows 10后,我创建了我的管理员用户Miha Šušterši?.现在,当我安装需要修改环境变量PATH的程序时,大多数程序都没有添加.例如,这发生在MongoDB和Git上,但npm正常添加.

我认为这是变量路径中的空白问题.我尝试将用户名重命名为M.Sustersic,但系统文件夹Users \MihaŠušteršič\没有更新.

有没有办法让我自动更改此文件夹名称(因此\ Users \MihaŠušteršič\ AppData的其余应用程序依赖项不会被窃听)或者我是否需要重新安装Windows?

我还缺少其他的东西吗?我尝试自己添加依赖项,但到目前为止没有任何工作.

谢谢您的帮助

path windows-10

9
推荐指数
2
解决办法
2万
查看次数