Hi I am having trouble running any tests using pac...
# pact-js
a
Hi I am having trouble running any tests using pact. I am not trying to send my pacts to pactflow yet, I am just trying to get them to run first I have 3 files User.js
Copy code
export class User {
    constructor({id, name, age}) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
}
API.js
Copy code
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));

export class API {
  constructor(url) {
    if (url === undefined || url === "") {
      url = '<http://localhost:3000>';
    }
    if (url.endsWith("/")) {
      url = url.substr(0, url.length - 1)
    }
    this.url = url
  }

  fetchUser = async url => {
      fetch(url)
      .then(res => res.json())
      .then(res => console.log(res))
      .catch(e => console.log("Error from response: ", e))
  }

  generateAuthToken() {
    return "Bearer " + new Date().toISOString()
  }
}

export default new API('<http://localhost:3000>');
test.pact.spec.js
Copy code
import { Pact } from '@pact-foundation/pact';
import { API } from './API';
import { Matchers } from '@pact-foundation/pact';
import { User } from './User';
const { eachLike, like, regex } = Matchers;

const mockProvider = new Pact({
  consumer: 'User-frontend',
  provider: 'Nodejs-backend',
  port: 1234
});

describe('API Pact test', () => {
  beforeAll(() => mockProvider.setup());
  afterEach(() => mockProvider.verify());
  afterAll(() => mockProvider.finalize());

  describe('retrieving a product', () => {
    test('ID 10 exists', async () => {
      // Arrange
      const expectedProduct = { id: '12', name: 'Sally', age: '32'}



      await mockProvider.addInteraction({
        state: 'a user with ID 12 exists',
        uponReceiving: 'a request to get a user',
        withRequest: {
          method: 'GET',
          path: '/user/12',
          headers: {
            Authorization: like('Bearer 2019-01-14T11:34:18.045Z'),
          },
        },
        willRespondWith: {
          status: 200,
          headers: {
            'Content-Type': regex({generate: 'application/json; charset=utf-8', matcher: 'application/json;?.*'}),
          },
          body: like(expectedProduct),
        },
      });

      // Act
      const api = new API(mockProvider.mockService.baseUrl);
      const product = await api.fetchUser('10');

      // Assert - did we get the expected response
      expect(product).toStrictEqual(new Product(expectedProduct));
    });

    
  });
});
How would I run the test locally in my cmd? Any help is appreciated
t
What test framework are you using?
You run the test with that
a
what do you mean test framework?
t
toStrictEqual
is Jest, so I reckon your test framework is jest
Also, what is the reason behind this import?
Copy code
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
a
Im using node, node doesn't have fetch
t
yes, but normally you would just
import fetch from 'node-fetch';
a
idk I saw it on the node-fetch documentation so i copy pasted
it works anyways
t
See here for a fully working example with jest - https://github.com/pact-foundation/pact-js/tree/master/examples/jest
It's unrelated to the problem you're having, but the import you have copy pasted is a dynamic import, and if you don't need it, it's probably better to just do a standard ESM import. See the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import
On your problem: Pact does not come with a test runner, so you need to run a pact test with one. Usually people just use whatever test runner they're using for unit tests - jest is by far the most popular, then mocha/chai. There are others, but they're less popular. See the examples directory I linked for other test runners
a
riiiiggghhhtt makes sense, thank you
Appreciate your help man
t
You're welcome. If you are indeed using jest, then you might like to check out the example I linked - it uses
jest-pact
which you don't need to use, but it substantially reduces the boilerplate setup in a pact test
aaand if you're using mocha, then we also have
mocha-pact
which does the same thing
a
To be honest, I saw the terms jest and mocha thrown around, I didn't really understand what they were, the majority of the code in the test file is copied and pasted
Which is why I was confused when you asked me if I was using jest
t
in your package.json, probably you've got a
script
with a
test
inside it. That will tell you what test runner you're using
eg here
sorry, it's
scripts
not
script
a
It worked, thank you 🙏
t
Awesome! Glad to help
a
One more q if you dont mind @Timothy Jones Does the syntax for writing a test change based on the test runner, or does it always stay the same
m
The node JS syntax won't be different, but the API and methods available might. Mocha and Jest are very similar except the hooks/lifecycle methods are slightly different. Best to read the relevant test framework guides.
💯 1
a
Thank you
👍 1