Using mocks in multiple test files fails
danmana opened this issue · comments
Checklist
- I have read Caveats documentation and didn't find a solution for this problem there.
Bug description
If we have mocks in multiple files, some of the test suites are failing.
If we run each file individually the tests succeed.
If we run mocha with --parallel
it also works
See repro here: https://github.com/danmana/mocha-aws-sdk-client-mock
npm run mocha -- tests/one*.js
works
npm run mocha -- tests/two*.js
works
npm run mocha -- tests/*.js
npm run mocha -- tests/*.js --parallel
works
Also if we put all tests in the same file, it works.
The tests are pretty straight forward
const { ListBucketsCommand, S3Client } = require('@aws-sdk/client-s3');
const { mockClient } = require('aws-sdk-client-mock');
const assert = require('assert');
const mock = mockClient(S3Client);
describe('one', () => {
let client;
beforeEach(() => {
mock.reset();
client = new S3Client();
});
it('should work', async () => {
mock.on(ListBucketsCommand).resolves({});
const result = await client.send(new ListBucketsCommand());
assert.deepEqual(result, {});
});
});
This is probably due to the way mocha runs the tests, but I can't figure out how to fix it.
Environment
- Node version: v14.18.0
- Typescript version: 6.14.15
- AWS SDK v3 Client mock version:
- AWS JS SDK libs and versions:
- "@aws-sdk/client-s3": "^3.41.0",
- "aws-sdk-client-mock": "^0.5.6",
Thank you for the detailed description and repo with reproduction!
The problem seems to be that the S3Client
mock from the first test file is overridden by the mock from the second test file. Apparently Mocha does not create separate environments for each test file.
The solution is to move mockClient()
method to beforeEach()
block. This way the mock will be created and configured for each of the tests.
const { ListBucketsCommand, S3Client } = require('@aws-sdk/client-s3');
const { mockClient } = require('aws-sdk-client-mock');
const assert = require('assert');
describe('one', () => {
let mock;
let client;
beforeEach(() => {
mock = mockClient(S3Client);
client = new S3Client();
});
it('should work', async () => {
mock.on(ListBucketsCommand).resolves({});
const result = await client.send(new ListBucketsCommand());
assert.deepEqual(result, {});
});
});
I will add this to the caveats section of the readme.
This is not an issue with Jest, which probably separates execution environments for each test file.