在 TS 中使用 Jest 模拟细分分析

Mocking Segment Analytics with Jest in TS

我正在尝试编写一个单元测试来检查是否调用了 Analytics 的 .track 方法。由于某种原因,测试一直失败,尽管通过 http 调用函数确实触发了调用。我不确定是不是我嘲笑错了,或者可能是什么问题?

index.ts:

import { Request } from "../types"
import { getSecret } from "../src/secrets"
import Analytics from "analytics-node"

const logger = (req: Request) => {
    const analytics = new Analytics(<string>process.env.WRITE_KEY);
    return analytics.track({
        userId: req.userId
    });
}

export default logger

index.test.ts:

jest.mock('analytics-node');
import { Request } from "../types"
import logger from "./index"
import Analytics from "analytics-node"

const mockAnalytics = new Analytics(process.env.WRITE_KEY = 'test');

describe('Logger tests', () => {
    it(`Should call analytics.track`, () => {
        const request: Request = {
            userId: 23
        }
        return logger(request).then(() => {
            expect(mockAnalytics.track).toHaveBeenCalled()
        });
    });
});

您正在通过调用 jest.mock('analytics-node') 使用 Automatic mock

Calling jest.mock('analytics-node') returns a useful "automatic mock" you can use to spy on calls to the class constructor and all of its methods. It replaces the ES6 class with a mock constructor and replaces all of its methods with mock functions that always return undefined. Method calls are saved in theAutomaticMock.mock.instances[index].methodName.mock.calls.

例如

index.ts:

import Analytics from 'analytics-node';

export interface Request {
  userId: string | number;
}

const logger = (req: Request) => {
  const analytics = new Analytics(<string>process.env.WRITE_KEY);
  return analytics.track({
    userId: req.userId,
    anonymousId: 1,
    event: '',
  });
};

export default logger;

index.test.ts:

import logger, { Request } from './';
import Analytics from 'analytics-node';

jest.mock('analytics-node');
const mockAnalytics = Analytics as jest.MockedClass<typeof Analytics>;

describe('Logger tests', () => {
  afterAll(() => {
    jest.resetAllMocks();
  });
  it(`Should call analytics.track`, () => {
    const WRITE_KEY = process.env.WRITE_KEY;
    process.env.WRITE_KEY = 'test key';
    const request: Request = {
      userId: 23,
    };
    logger(request);
    expect(mockAnalytics).toBeCalledWith('test key');
    expect(mockAnalytics.mock.instances[0].track).toHaveBeenCalled();
    process.env.WRITE_KEY = WRITE_KEY;
  });
});

单元测试结果:

 PASS  examples/65412302/index.test.ts
  Logger tests
    ✓ Should call analytics.track (4 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.954 s