我正在尝试通过 Pact.js 模拟Angular Rest API,但遇到错误Failed: Actual interactions do not match expected interactions for mock MockService.
我的原始API被调用,而不是被模拟的服务器。 当我尝试获取http://localhost:1234/users(模拟的协议服务器api)时。
我得到结果:{"message":"No interaction found for GET /","interaction_diffs":[]}
预期的行为:实际的Rest API调用被转移到了模拟服务器,我应该得到模拟的输出。 (请参见下面的代码中的ExpectedUser。),而不是实际的api结果。
下面是我的代码:
Karma.conf.js
...
pact: [{
cors: true,
port: 1234,
consumer: "ui",
provider: "usersservice",
host: '127.0.0.1',
dir: "pacts/",
spec: 2
}],
proxies: {
// below is a fake rest API I'm trying to mock.
'http://jsonplaceholder.typicode.com/users': 'http://localhost:1234/users'
},
...
user.service.pact.spec.ts
import { TestBed } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import { UsersService } from './shared/users.service';
import { User } from './shared/user';
import { PactWeb, Matchers } from '@pact-foundation/pact-web';
describe('UsersService pack test', () => {
let provider;
beforeAll(function (done) {
provider = new PactWeb({
cors: true,
consumer: 'ui',
provider: 'users-service',
port: 1234,
host: '127.0.0.1',
});
// required for slower CI environments
setTimeout(done, 2000);
// Required if run with `singleRun: false`
provider.removeInteractions();
});
afterAll(function (done) {
provider.finalize()
.then(function () {
done();
}, function (err) {
done.fail(err);
});
});
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule
],
providers: [
UsersService
],
});
});
afterEach((done) => {
provider.verify().then(done, e => done.fail(e));
});
describe('getUsers()', () => {
const expectedUser: User[] = [{
"id": 9,
"name": "test user",
"email": "test@user.xyz",
"phone": "1-999-999-9999 x99999",
}];
beforeAll((done) => {
provider.addInteraction({
state: `provider return a expected user array`,
uponReceiving: 'a request to GET a person',
withRequest: {
method: 'GET',
path: 'http://jsonplaceholder.typicode.com/users',
},
willRespondWith: {
status: 200,
body: expectedUser, // to respond with defined data.
headers: {
'Content-Type': 'application/json'
}
}
}).then(done, error => done.fail(error));
});
it('should get Person array', (done) => {
const usersService: UsersService = TestBed.get(UsersService);
usersService.getUsers().subscribe(response => {
console.log(response) // this logs actual API response not mocked.
expect(response).toEqual(expectedUser); // this fails
done();
}, error => {
done.fail(error);
});
});
});
});
我遵循了以下资源,但无法创建并重定向到模拟API
https://reflectoring.io/consumer-driven-contracts-with-angular-and-pact/
https://github.com/thombergs/code-examples/tree/master/pact/pact-angular
答案 0 :(得分:0)
据我所知,在测试设置中,您没有告诉您代码的API端点是不同的-您需要告诉http库/客户端使用pact API,而不是您的真实API(Pact不会不会自动劫持您的http客户端)。
此外,您的WithRequest
似乎包含非法路径。您不能在契约合同中覆盖主机名。