javascript - 我可以模拟/监视非纯函数的父作用域中存在的变量值吗?

标签 javascript mocking jestjs

let state = 'Monday';
export function greet() {
  return 'hello ' + state;
}

↑ 凭借良好的编码实践,您不会遇到这样的非纯函数,但由于某些特殊原因我遇到了。

然后,开个 Jest :

import { greet } from './functions';

test('a', () => {
  expect(greet()).toBe('hello Monday');
});

test('b', () => {
  let state = 'Tuesday';
  expect(greet()).toBe('hello Tuesday'); // fail! Still 'hello Monday'
});

在这种情况下,我如何模拟状态?

最佳答案

您可以使用rewire将模块作用域中定义的私有(private)变量替换为模拟变量。

The current version of rewire is only compatible with CommonJS modules. see limitations

因此下面的示例将 ES 模块更改为 CommonJS 模块。

例如 functions.js:

let state = 'Monday';
function greet() {
  return 'hello ' + state;
}

exports.greet = greet;

functions.test.js:

const rewire = require('rewire');
const functions = rewire('./functions');

describe('60763037', () => {
  test('a', () => {
    expect(functions.greet()).toBe('hello Monday');
  });

  test('b', () => {
    functions.__set__('state', 'Tuesday');
    expect(functions.greet()).toBe('hello Tuesday');
  });
});

单元测试结果:

 PASS  stackoverflow/60763037/functions.test.js
  60763037
    ✓ a (3ms)
    ✓ b (1ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        5.04s

关于javascript - 我可以模拟/监视非纯函数的父作用域中存在的变量值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60763037/

相关文章:

javascript - Jest + process.env.NODE_ENV 未正确测试

javascript - 从后台代码加载时运行 JS 方法

javascript - js 文件未加载但执行了下一个脚本?

php - 功能测试 - 模拟服务不会持久存在于服务容器中

unit-testing - 为什么我的单元测试需要一个模拟框架?

reactjs - Enzyme-如何设置内部组件的状态?

unit-testing - 使用 axios-mock-adapter 模拟 axios 得到未定义的响应

javascript - 在 Three.js 中调整 View 大小会缩小图像

javascript - 如何在一页中定义两个 Angular 应用程序/模块?

c# - 使用 Moq 模拟扩展方法