我在这个测试中遇到了一个奇怪的问题:
import Deal from "../src/models/Deal";
import apiProducts from "../__mocks__/api/products";
describe("Deal", () => {
  describe("Deal.fromApi", () => {
    it("takes an api product and returns a Deal", () => {
      const apiDeal = apiProducts[0];
      const newDeal = Deal.fromApi(apiDeal);
      const expected = expectedDeal();
      expect(newDeal).toEqual(expected);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)
export default class Deal {
  // no constructor since we only ever create a deal from Deal.fromApi
  static fromApi(obj: Object): Deal {
    const deal = new Deal();
    deal.id = obj.id;
    deal.name = obj.name;
    deal.slug …Run Code Online (Sandbox Code Playgroud) 我是 vue 和 jest 测试的新手,在运行特定测试时不断收到此错误。我知道这是一个普遍错误,但我不确定如何深入了解并找出问题所在。
这是错误:
 Test suite failed to run
    Jest worker encountered 4 child process exceptions, exceeding retry limit
      at ChildProcessWorker.initialize (node_modules/jest-worker/build/workers/ChildProcessWorker.js:185:21)
Run Code Online (Sandbox Code Playgroud)
这是失败的测试:
test("signupAsUser logs results if email is provided", async () => {
  const consoleSpy = jest.spyOn(console, "log");
  const email = ref("testuser@scoutapm.com");
  const { signupAsUser } = useSignup(email);
  await signupAsUser();
  expect(consoleSpy).toHaveBeenCalledWith("USER:", mockSignup);
});
Run Code Online (Sandbox Code Playgroud)
这是正在测试的文件。vue 文件:
<!--
  View for user signup operations.
-->
<template lang="pug">
.Signup
    .Signup__focus
        .Signup__title Sign Up
            .Signup__form
                .Signup__field
                    va-input.Signup__emailInput(
                       type="email",
                      name="email",
                      placeholder="Email",
                      v-model="email",
                      @keyup.enter="signupAsUser()" …Run Code Online (Sandbox Code Playgroud) 我正在使用Jest框架并拥有一个测试套件.我想关闭/跳过我的一个测试.
谷歌搜索文档没有给我答案.
您知道要检查的答案或信息来源吗?
我使用webpack开发一个React组件.这是一个简单的版本:
'use strict';
require('./MyComponent.less');
var React = require('react');
var MyComponent = React.createClass({
  render() {
    return (
      <div className="my-component">
        Hello World
      </div>
    );
  }
});
module.exports = MyComponent;
Run Code Online (Sandbox Code Playgroud)
现在,我想使用jest测试这个组件.以下是我的相关内容package.json:
"scripts": {
  "test": "jest"
},
"jest": {
  "rootDir": ".",
  "testDirectoryName": "tests",
  "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
  "unmockedModulePathPatterns": [
    "react"
  ]
}
Run Code Online (Sandbox Code Playgroud)
运行时npm test,我收到以下错误:
SyntaxError:/Users/mishamoroshko/react-component/src/tests/MyComponent.js:/Users/mishamoroshko/react-component/src/MyComponent.js:/Users/mishamoroshko/react-component/src/MyComponent.less:Unexpected令牌ILLEGAL
看起来webpack需要require('./MyComponent.less')在jest运行测试之前进行处理.
我想知道我是否需要使用像jest-webpack这样的东西.如果是,有没有办法指定多个scriptPreprocessors?(注意我已经使用过babel-jest)
我正在尝试测试我的锚标签。一旦我点击它,我想看看它是否window.location.href是我所期望的。
我尝试渲染锚点,单击它,然后进行测试window.location.href:
test('should navigate to ... when link is clicked', () => {
  const { getByText } = render(<a href="https://test.com">Click Me</a>);
  const link = getByText('Click Me');
  fireEvent.click(link);
  expect(window.location.href).toBe("https://www.test.com/");
});
Run Code Online (Sandbox Code Playgroud)
我期待测试通过,但 window.location.href 只是"http://localhost/"意味着它没有因任何原因得到更新。我什至尝试用 包装我的期望await wait,但这也不起作用。我找不到关于使用react-testing-library. 也许有比我正在做的更好的方法来测试它们。???
在Jest中有没有办法模拟全局对象,比如navigator,Image*?我已经非常放弃了这一点,并将其留给了一系列可模拟的实用方法.例如:
// Utils.js
export isOnline() {
    return navigator.onLine;
}
Run Code Online (Sandbox Code Playgroud)
测试这个微小的功能很简单,但很苛刻,而且根本不具有确定性.我可以获得75%的方式,但这是我可以做的:
// Utils.test.js
it('knows if it is online', () => {
    const { isOnline } = require('path/to/Utils');
    expect(() => isOnline()).not.toThrow();
    expect(typeof isOnline()).toBe('boolean');
});
Run Code Online (Sandbox Code Playgroud)
另一方面,如果我对这个间接是好的,我现在可以navigator通过这些实用程序访问:
// Foo.js
import { isOnline } from './Utils';
export default class Foo {
    doSomethingOnline() {
        if (!isOnline()) throw new Error('Not online');
        /* More implementation */            
    }
}
Run Code Online (Sandbox Code Playgroud)
......并确定性地测试这样......
// Foo.test.js
it('throws when offline', () => {
    const Utils = require('../services/Utils');
    Utils.isOnline …Run Code Online (Sandbox Code Playgroud) 我是Jest的新手,我正在尝试使用它来测试函数是否被调用.我注意到mock.calls.length没有为每个测试重置但是累积.如何在每次测试前将其设为0?我不希望我的下一次测试取决于之前的结果.
我知道在Jest之前有一个 - 我应该使用它吗?重置mock.calls.length的最佳方法是什么?谢谢.
一个代码示例:
Sum.js:
import local from 'api/local';
export default {
  addNumbers(a, b) {
    if (a + b <= 10) {
      local.getData();
    }
    return a + b;
  },
};
Run Code Online (Sandbox Code Playgroud)
Sum.test.js
import sum from 'api/sum';
import local from 'api/local';
jest.mock('api/local');
// For current implementation, there is a difference 
// if I put test 1 before test 2. I want it to be no difference
// test 1
test('should not to call local if sum is more than 10', () …Run Code Online (Sandbox Code Playgroud) 我有一个反应组件(这是为了证明问题而简化):
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
Run Code Online (Sandbox Code Playgroud)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)
所以我的问题是,如何用酶正确模拟组分方法?
正确模拟以下示例的最佳方法是什么?
问题是在导入时间之后,foo保持对原始未引用的引用bar.
module.js:
export function bar () {
    return 'bar';
}
export function foo () {
    return `I am foo. bar is ${bar()}`;
}
Run Code Online (Sandbox Code Playgroud)
module.test.js:
import * as module from '../src/module';
describe('module', () => {
    let barSpy;
    beforeEach(() => {
        barSpy = jest.spyOn(
            module,
            'bar'
        ).mockImplementation(jest.fn());
    });
    afterEach(() => {
        barSpy.mockRestore();
    });
    it('foo', () => {
        console.log(jest.isMockFunction(module.bar)); // outputs true
        module.bar.mockReturnValue('fake bar');
        console.log(module.bar()); // outputs 'fake bar';
        expect(module.foo()).toEqual('I am foo. bar is fake bar');
        /**
         * …Run Code Online (Sandbox Code Playgroud) 我在带有打字稿的 react router v5.1.2 中使用 UseHistory 钩子吗?运行单元测试时,我遇到了问题。
类型错误:无法读取未定义的属性“历史”。
import { mount } from 'enzyme';
import React from 'react';
import {Action} from 'history';
import * as router from 'react-router';
import { QuestionContainer } from './QuestionsContainer';
describe('My questions container', () => {
    beforeEach(() => {
        const historyHistory= {
            replace: jest.fn(),
            length: 0,
            location: { 
                pathname: '',
                search: '',
                state: '',
                hash: ''
            },
            action: 'REPLACE' as Action,
            push: jest.fn(),
            go: jest.fn(),
            goBack: jest.fn(),
            goForward: jest.fn(),
            block: jest.fn(),
            listen: jest.fn(),
            createHref: jest.fn()
        };//fake …Run Code Online (Sandbox Code Playgroud) jestjs ×10
javascript ×6
reactjs ×4
unit-testing ×3
enzyme ×2
testing ×2
typescript ×2
anchor ×1
babel-jest ×1
dependencies ×1
href ×1
mocking ×1
node.js ×1
react-router ×1
vue.js ×1
webpack ×1