是否有一个玩笑配置会使 console.warn 上的测试失败?

问题描述 投票:0回答:6

如何配置笑话测试以因警告而失败?

console.warn('stuff');
// fail test
jestjs
6个回答
31
投票

您可以使用这个简单的覆盖:

let error = console.error

console.error = function (message) {
  error.apply(console, arguments) // keep default behaviour
  throw (message instanceof Error ? message : new Error(message))
}

您可以使用 Jest setupFiles 使其在所有测试中可用。

package.json

"jest": {
    "setupFiles": [
      "./tests/jest.overrides.js"
    ]
}

然后将片段放入

jest.overrides.js


9
投票

有一个有用的 npm 包可以帮助您实现这一目标:jest-fail-on-console

易于配置。

安装

npm i -D jest-fail-on-console

配置

在 Jest 的 setupFilesAfterEnv 选项中使用的文件中,添加以下代码:

import failOnConsole from 'jest-fail-on-console'

failOnConsole()

// or with options:
failOnConsole({ shouldFailOnWarn: false })

9
投票

对于那些使用create-react-app,不想运行

npm run eject
的人,可以将以下代码添加到
./src/setupTests.js

global.console.warn = (message) => {
  throw message
}

global.console.error = (message) => {
  throw message
}

现在,当消息传递到

console.warn
console.error
时,玩笑将会失败。

create-react-app 文档 - 初始化测试环境


7
投票

我最近使用 jest.spyOn

 中引入的 
v19.0.0
 来实现此功能,以模拟 
warn
console
方法(通过
global
上下文/对象访问)。

那么可以

expect
模拟的
warn
没有被调用,如下所示。

describe('A function that does something', () => {
  it('Should not trigger a warning', () => {
    var warn = jest.spyOn(global.console, 'warn');

    // Do something that may trigger warning via `console.warn`
    doSomething();

    // ... i.e.
    console.warn('stuff');

    // Check that warn was not called (fail on warning)
    expect(warn).not.toHaveBeenCalled();

    // Cleanup
    warn.mockReset();
    warn.mockRestore();
  });
});

0
投票

我决定发布一个基于 user1823021 答案的完整示例

describe('#perform', () => {
  var api
  // the global.fetch is set to jest.fn() object globally
  global.fetch = jest.fn()
  var warn = jest.spyOn(global.console, 'warn');
  beforeEach(function() {
    // before every test, all mocks need to be resetted
    api = new Api()
    global.fetch.mockReset()
    warn.mockReset()
  });

  it('triggers an console.warn if fetch fails', function() {
    // In this test fetch mock throws an error
    global.fetch.mockImplementationOnce(() => {
      throw 'error triggered'
    })
    // I run the test
    api.perform()
    // I verify that the warn spy has been triggered
    expect(warn).toHaveBeenCalledTimes(1);
    expect(warn).toBeCalledWith("api call failed with error: ", "error triggered")
  });

  it('calls fetch function', function() {
    // I create 2 more mock objects to verify the fetch parameters
    const url = jest.fn()
    const config = jest.fn()
    api.url = url
    api.config = config
    // I run the test
    api.perform()
    // I verify that fetch has been called with url and config mocks
    expect(global.fetch).toHaveBeenCalledTimes(1)
    expect(global.fetch).toBeCalledWith(url, config)
    expect(warn).toHaveBeenCalledTimes(0)
  });
})

我正在测试的

#perform
方法

class Api {
  constructor(auth) {
    this._credentials = auth
  }

  perform = async () => {
    try {
      return await fetch(this.url, this.config)
    } catch(error) {
      console.warn('api call failed with error: ', error)
    }
  }
}

0
投票

您可以在运行

CI=true
之前设置环境变量
jest
,这将导致它除了错误之外还无法通过警告测试。

运行

test
文件夹中所有测试文件的示例:

CI=true jest ./test

Github Actions 等自动化 CI/CD 管道默认将

CI
设置为
true
,这可能是单元测试在抛出警告时在本地计算机上通过但在管道中失败的原因之一。

(这里是关于默认环境变量的 Github Actions 文档:https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables

© www.soinside.com 2019 - 2024. All rights reserved.