小编Can*_*nta的帖子

'.toMatchObject'和'objectContaining'之间有什么区别?

我写了以下测试:

it('Can decrement the current step', function () {
    expect(reducer(TestState, { type: 'GOTO_PREVIOUS_STEP' })).toMatchObject({ currentStep: 4 });
});

it('Can decrement the current step v2', function () {
    expect(reducer(TestState, { type: 'GOTO_PREVIOUS_STEP' })).toEqual(expect.objectContaining({ currentStep: 4 }));
});
Run Code Online (Sandbox Code Playgroud)

他们俩似乎都通过了考试,他们之间有什么区别吗?他们之间有性能影响吗?

javascript jestjs

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

如何在jest中模拟导出的const

我有一个依赖于导出const变量的文件.此变量设置为true但如果需要,可以false手动设置以防止下游服务请求它时的某些行为.

我不知道如何const在Jest中模拟变量,以便我可以更改它的值来测试truefalse条件.

例:

//constants module
export const ENABLED = true;

//allowThrough module
import { ENABLED } from './constants';

export function allowThrough(data) {
  return (data && ENABLED === true)
}

// jest test
import { allowThrough } from './allowThrough';
import { ENABLED } from './constants';

describe('allowThrough', () => {
  test('success', () => {
    expect(ENABLED).toBE(true);
    expect(allowThrough({value: 1})).toBe(true);
  });

  test('fail, ENABLED === false', () => {
    //how do I override the …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing reactjs jestjs

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

开玩笑:计时器和承诺不能正常工作.(setTimeout和async函数)

关于此代码的任何想法

jest.useFakeTimers() 

it('simpleTimer', async () => {
  async function simpleTimer(callback) {
    await callback()    // LINE-A without await here, test works as expected.
    setTimeout(() => {
      simpleTimer(callback)
    }, 1000)
  }

  const callback = jest.fn()
  await simpleTimer(callback)
  jest.advanceTimersByTime(8000)
  expect(callback).toHaveBeenCalledTimes(9)
}
Run Code Online (Sandbox Code Playgroud)

```

失败了

Expected mock function to have been called nine times, but it was called two times.
Run Code Online (Sandbox Code Playgroud)

但是,如果我await从LINE-A中删除,则测试通过.

Promise和Timer不能正常工作吗?

我认为开玩笑的原因是等待第二个承诺来解决.

javascript testing jestjs

25
推荐指数
2
解决办法
7235
查看次数

测试反应组件包含在withRouter中(最好使用jest /酶)

我有一个React组件,它包含在高阶组件withRouter中,如下所示:

module.exports = withRouter(ManageProfilePage);
Run Code Online (Sandbox Code Playgroud)

我的路线如下:

<Route path="/" component={AdrApp}>
    <IndexRoute component={Login}/>
    <Route component={CheckLoginStatus}>
        <Route path="manage-profiles/:profileId" component=
        {ManageProfilesPage}/>
     </Route>
    <Route path="*" component={notFoundPage}/>
</Route>
Run Code Online (Sandbox Code Playgroud)

我需要使用一次Router生命周期方法,这就是我需要withRouter的原因:

class ManageProfilePage extends React.Component {
    componentDidMount() {
    this.props.router.setRouteLeaveHook(this.props.route, () => {
      ...
    })
    render(){
    ... 
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要使用Jest/Enzyme测试这个组件,我编写了如下测试用例:

describe('manage profile page test suite', () => {


    it('snapshot test', () => {

        const setRouteLeaveHook =jest.fn();

        let wrapper = shallow(
            <ManageProfilePage params={{id : 25, router: 
        setRouteLeaveHook}}/>
        );
      expect(wrapper).toMatchSnapshot();
    })
   }) 
Run Code Online (Sandbox Code Playgroud)

问题是它没有渲染一个层次.我正在粘贴下面的快照:

exports[`manage drug term page test suites snapshot test 1`] …
Run Code Online (Sandbox Code Playgroud)

unit-testing reactjs jestjs react-router enzyme

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

ts-jest不承认es6进口

我正在为反应代码库添加打字稿支持,虽然应用程序工作正常,但是jest测试在整个地方都失败了,显然没有认识到有关es6语法的东西.

我们正在使用ts-jest.下面是我正在尝试处理jest的测试设置文件时的错误消息.

 FAIL  src/data/reducers/reducers.test.js
  ? Test suite failed to run

    /Users/ernesto/code/app/react/setupTests.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import './polyfills';
                                                                                                    ^^^^^^^^^^^^^

    SyntaxError: Unexpected string

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
Run Code Online (Sandbox Code Playgroud)

它无法识别一个简单的import './polyfills',说引用的字符串是意外的.

这些是我的设置:

package.json中的jest配置

"jest": {
  "setupTestFrameworkScriptFile": "<rootDir>/app/react/setupTests.js",
  "transform": {
    "^.+\\.tsx?$": "ts-jest"
  },
  "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
  "moduleFileExtensions": [
    "ts",
    "tsx",
    "js",
    "jsx",
    "json",
    "node"
  ]
},
Run Code Online (Sandbox Code Playgroud)

tsconfig.json

{
  "compilerOptions": {
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es6", "dom"],
    "module": "es6",
    "moduleResolution": "node",
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "target": "es5",
    "jsx": "react",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true, …
Run Code Online (Sandbox Code Playgroud)

typescript jestjs babeljs es6-modules

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

projects.map不是jest-cli的函数

我正在写一个反应应用程序并用开玩笑测试它.但是,每当我jest从终端运行命令时,我都会出现此错误.

TypeError: projects.map is not a function
    at Object.<anonymous> (/Users/DavidHu/Desktop/coding/projects/swapnow/node_modules/jest-cli/build/cli/runCLI.js:172:28)
    at next (native)
    at step (/Users/DavidHu/Desktop/coding/projects/swapnow/node_modules/jest-cli/build/cli/runCLI.js:18:30)
    at /Users/DavidHu/Desktop/coding/projects/swapnow/node_modules/jest-cli/build/cli/runCLI.js:34:14
    at Object.<anonymous> (/Users/DavidHu/Desktop/coding/projects/swapnow/node_modules/jest-cli/build/cli/runCLI.js:15:12)
    at Object.module.exports [as runCLI] (/Users/DavidHu/Desktop/coding/projects/swapnow/node_modules/jest-cli/build/cli/runCLI.js:2 03:17)
    at Object.run (/Users/DavidHu/.nvm/versions/node/v6.2.1/lib/node_modules/jest-cli/build/cli/index.js:42:17)
    at Object.<anonymous> (/Users/DavidHu/.nvm/versions/node/v6.2.1/lib/node_modules/jest-cli/bin/jest.js:16:25)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
Run Code Online (Sandbox Code Playgroud)

我进入node_modules查看导致错误的代码行,projects是项目当前路径的字符串.

这是我的开玩笑配置 package.json

  "jest": {
    "transform": {
      ".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ]
  }
Run Code Online (Sandbox Code Playgroud)

有没有人遇到过这个错误,知道如何修复它?

javascript typescript reactjs jestjs

19
推荐指数
2
解决办法
4516
查看次数

使用Jest使用props模拟React组件

我有一个React组件,其中包含一些依赖于访问Redux存储等的其他组件,这会在执行完整的Enzyme安装时导致问题.让我们说这样的结构:

import ComponentToMock from './ComponentToMock';

<ComponentToTest>
  ...some stuff
  <ComponentToMock testProp="This throws a warning" />
</ComponentToTest>
Run Code Online (Sandbox Code Playgroud)

我想使用Jest的.mock()方法来模拟子组件,因此它不是测试的关注点.

我知道我可以用以下方法嘲笑一个直的组件:

jest.mock('./ComponentToMock', () => 'ComponentToMock');

但是,由于此组件通常会收到道具,因此React会感到不安,并会发出有关未知道具(在这种情况下testProp)被传递给的警告<ComponentToMock />.

我试图返回一个函数,但是由于它被挂起,你无法在Jest模拟中返回JSX(我可以告诉).在这种情况下它会引发错误.

所以我的问题是我怎么能

a)ComponentToMock忽略传递给它的道具,或者

b)返回一个React组件,该组件可用于模拟我不担心测试的子组件.

或者,还有更好的方法?

unit-testing mocking reactjs jestjs enzyme

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

React&Enzyme:为什么不能在每个()工作之前?

我正在编写我的第一个React测试并遇到一个我的beforeEach声明不起作用的问题.这是我的测试文件:

import React from 'react';
import { shallow } from 'enzyme';
import Home from '../components/Home';
import IntroText from '../components/IntroText';
import Form from '../components/Form';

describe('<Home />', () => {
  beforeEach(() => {
    const wrapper = shallow(<Home />);
  });

  it('renders the IntroText component', () => {
    expect(wrapper.find(IntroText).length).toBe(1);
  });

  it('renders the Form component', () => {
    expect(wrapper.find(Form).length).toBe(1);
  });
});
Run Code Online (Sandbox Code Playgroud)

这是我的相关部分package.json:

"devDependencies": {
  "babel-jest": "^18.0.0",
  "babel-preset-es2015": "^6.22.0",
  "babel-preset-react": "^6.23.0",
  "jest": "^18.1.0",
  "react-scripts": "0.9.0",
  "react-test-renderer": "^15.4.2"
 },
"dependencies": {
  "enzyme": "^2.7.1", …
Run Code Online (Sandbox Code Playgroud)

testing reactjs jestjs enzyme

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

尝试测试create-react-app项目时,"ReferenceError:document not defined"

这是我的__tests__/App.js档案:

import React from 'react';
import ReactDOM from 'react-dom';
import App from '../src/containers/App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
});

// sanity check
it('one is one', () => {
  expect(1).toEqual(1)
});
Run Code Online (Sandbox Code Playgroud)

这是我在运行时得到的输出yarn test:

FAIL  __tests__/App.js
  ? renders without crashing

    ReferenceError: document is not defined

      at Object.<anonymous>.it (__tests__/App.js:6:15)

  ? renders without crashing (1ms)
  ? one is one

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs create-react-app

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

Vue.js Vuetify,与Jest一起运行我的第一次单元测试

Herea是我的第一个测试:

Heading.spec.js

    import Vuetify from "vuetify";
    import { shallowMount, createLocalVue } from "@vue/test-utils";
    import router from "@/router";
    import i18n from "@/locales";
    import Heading from "@/components/Home/Heading.vue";

    describe("Heading.vue", () => {
      let wrapper;

      beforeEach(() => {
        const localVue = createLocalVue()
        localVue.use(router)
        localVue.use(Vuetify)
        localVue.filter("translate", function(value) {
          if (!value) return "";
          value = "lang.views.global." + value.toString();
          return i18n.t(value);
        });

        wrapper = shallowMount(Heading, { localVue: localVue, router, i18n });
      });

      it("should contains default heading", () => {
        console.log ('WRAPPER: ', wrapper)
        // const heading = …
Run Code Online (Sandbox Code Playgroud)

unit-testing vue.js jestjs vuetify.js

14
推荐指数
1
解决办法
4235
查看次数