Jest 测试用例更新了下一个测试用例的模拟数据对象

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

Helpers.spec.js 文件

describe('Helpers', () => {
  beforeAll(() => {
    jest.clearAllMocks();

    jest.mock('./operations', () => ({
      Operators: jest.fn()
    }));
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  const mockData = [ { id: 1 }, { id: 2 }, { id: 3 } ];

  it('Should return a id 1', async () => {
    Operations.getData = jest.fn().mockResolvedValue(mockData);
    const response = await Helpers.execute();
    expect(response.id).toBe(1);
  });

  it('Should return a id 1 with true flag', async () => {
    Operations.getData = jest.fn().mockResolvedValue(mockData);
    Operations.track = jest.fn().mockResolvedValue({});

    const response = await Helpers.execute(true);
    expect(response.id).toBe(1);
  });
});

Helpers.js

import { getData, track } from `./operations`;

export class Helpers {
  static async execute(request) {
    if(request)
      track();

    const data = getData();
    return data.shift();
  }
}

操作.js

async function getData() {
  // Operation to return the data
}

async function track() {
  // Operation to track the data
}

这里第二个测试用例失败,因为它返回 id 2。出于某种原因,当第二个测试用例当时正在运行时

mockData
由于第一个测试用例,数组已移动一次。

javascript unit-testing jestjs mocking babel-jest
1个回答
0
投票
  1. 您应该使用

    const data = await getData()
    ,因为
    getData
    功能是
    async

  2. 您应该为每个测试用例创建

    mockData
    ,以便一个测试用例中的变异(
    data.shift()
    )不会影响其他测试用例。

  3. jest.mock()
    放入测试文件的模块范围内。

helpers.js

import { getData, track } from './operations';

export class Helpers {
    static async execute(request) {
        if (request) track();

        const data = await getData();
        return data.shift();
    }
}

operations.js

export async function getData() {
    // Operation to return the data
}

export async function track() {
    // Operation to track the data
}

helpers.test.js

import { Helpers } from './helpers';
import { getData, track } from './operations';

jest.mock('./operations');

describe('Helpers', () => {
    afterEach(() => {
        jest.clearAllMocks();
    });


    it('Should return a id 1', async () => {
    const mockData = [{ id: 1 }, { id: 2 }, { id: 3 }];
        getData.mockResolvedValue(mockData);
        const response = await Helpers.execute();
        expect(response.id).toBe(1);
    });

    it('Should return a id 1 with true flag', async () => {
    const mockData = [{ id: 1 }, { id: 2 }, { id: 3 }];
        getData.mockResolvedValue(mockData);
        track.mockResolvedValue({});

        const response = await Helpers.execute(true);
        expect(response.id).toBe(1);
    });
});

测试结果:

 PASS  stackoverflow/77265044/helpers.test.js (6.052 s)
  Helpers
    ✓ Should return a id 1 (1 ms)
    ✓ Should return a id 1 with true flag

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        6.261 s
© www.soinside.com 2019 - 2024. All rights reserved.